<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!-- Dynamic Title and SEO -->
    <title id="page-title">xlcig Notebook - 免费在线数据可视化平台 | 无需下载，一键生成专业图表</title>
    <meta name="description" id="page-description" content="免费在线数据可视化工具，无需下载安装！支持CSV、Excel文件上传，一键在线生成专业图表、仪表板和数据报告。企业级数据分析平台，浏览器即用。Free online data visualization platform, no download required! Generate professional charts instantly.">
    <meta name="keywords" id="page-keywords" content="在线数据可视化,免费图表生成器,无需下载,在线制图工具,Excel在线分析,CSV可视化,数据分析工具,仪表板制作,在线生成,免费使用,浏览器工具,online data visualization,free chart generator,no download,web-based,instant charts">
    <meta name="author" content="xlcig Team">
    <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1">
    <meta name="googlebot" content="index, follow">
    
    <!-- 百度站长验证 -->
    <meta name="baidu_union_verify" content="a4190a6e7a5a121c5c373b197d5f7671">
    <meta name="language" content="zh-CN">
    <meta name="revisit-after" content="3 days">
    <meta name="generator" content="xlcig Notebook Online Platform">
    
    <!-- Geographic and Localization -->
    <meta name="geo.region" content="CN">
    <meta name="geo.placename" content="China">
    <meta name="geo.position" content="39.9042;116.4074">
    <meta name="ICBM" content="39.9042, 116.4074">
    
    <!-- Additional SEO -->
    <meta name="application-name" content="xlcig在线可视化">
    <meta name="msapplication-TileColor" content="#4A90E2">
    <meta name="theme-color" content="#4A90E2">
    <meta name="apple-mobile-web-app-title" content="xlcig在线分析">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    
    <!-- Canonical URL -->
    <link rel="canonical" href="https://your-domain.com/">
    <link rel="alternate" hreflang="zh-CN" href="https://your-domain.com/?lang=zh">
    <link rel="alternate" hreflang="en" href="https://your-domain.com/?lang=en">
    <link rel="alternate" hreflang="x-default" href="https://your-domain.com/">
    
    <!-- Open Graph / Facebook -->
    <meta property="og:type" content="website">
    <meta property="og:url" id="og-url" content="https://your-domain.com/">
    <meta property="og:title" id="og-title" content="xlcig Notebook - 免费在线数据可视化平台，无需下载一键生成图表">
    <meta property="og:description" id="og-description" content="免费在线数据可视化工具！上传CSV、Excel文件，浏览器中一键生成专业图表和仪表板。无需下载安装任何软件，企业级数据分析功能完全免费使用。">
    <meta property="og:image" content="https://your-domain.com/static/img/logo.png">
    <meta property="og:image:width" content="1200">
    <meta property="og:image:height" content="630">
    <meta property="og:image:alt" content="xlcig在线数据可视化平台截图">
    <meta property="og:site_name" content="xlcig Notebook">
    <meta property="og:locale" content="zh_CN">
    <meta property="og:locale:alternate" content="en_US">
    
    <!-- Twitter -->
    <meta property="twitter:card" content="summary_large_image">
    <meta property="twitter:url" id="twitter-url" content="https://your-domain.com/">
    <meta property="twitter:title" id="twitter-title" content="xlcig Notebook - 免费在线数据可视化，无需下载">
    <meta property="twitter:description" id="twitter-description" content="免费在线数据可视化工具！上传文件一键生成专业图表，无需下载安装任何软件">
    <meta property="twitter:image" content="https://your-domain.com/static/img/logo.png">
    <meta property="twitter:image:alt" content="xlcig在线数据可视化平台">
    <meta property="twitter:creator" content="@xlcig">
    <meta property="twitter:site" content="@xlcig">
    
    <!-- Dublin Core -->
    <meta name="DC.title" content="xlcig Notebook - 免费在线数据可视化平台">
    <meta name="DC.creator" content="xlcig Team">
    <meta name="DC.subject" content="在线数据可视化,免费图表生成,无需下载">
    <meta name="DC.description" content="专业的免费在线数据可视化分析平台，无需下载安装">
    <meta name="DC.publisher" content="xlcig Team">
    <meta name="DC.contributor" content="xlcig Development Team">
    <meta name="DC.date" content="2024">
    <meta name="DC.type" content="Interactive Resource">
    <meta name="DC.format" content="text/html">
    <meta name="DC.identifier" content="https://your-domain.com">
    <meta name="DC.language" content="zh-CN">
    <meta name="DC.coverage" content="全球用户">
    <meta name="DC.rights" content="免费使用">
    
    <!-- Favicon and App Icons -->
    <link rel="icon" type="image/png" sizes="32x32" href="/static/img/favicon.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/static/img/favicon.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/static/img/logo.png">
    <link rel="manifest" href="/manifest.json">
    <meta name="theme-color" content="#2c3e50">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="xlcig Analytics">
    
    <!-- Preconnect for Performance -->
    <link rel="preconnect" href="https://cdnjs.cloudflare.com">
    <link rel="preconnect" href="https://cdn.jsdelivr.net">
    <link rel="dns-prefetch" href="https://cdnjs.cloudflare.com">
    <link rel="dns-prefetch" href="https://cdn.jsdelivr.net">
    
    <!-- Structured Data for SEO -->
    <script type="application/ld+json" id="structured-data">
    {
        "@context": "https://schema.org",
        "@type": "WebApplication",
        "name": "xlcig Notebook",
        "alternateName": "xlcig在线数据可视化平台",
        "description": "免费在线数据可视化工具，无需下载安装！支持CSV、Excel文件上传，浏览器中一键生成专业图表、仪表板和数据报告。企业级数据分析功能完全免费。",
        "url": "https://your-domain.com",
        "logo": {
            "@type": "ImageObject",
            "url": "https://your-domain.com/static/img/logo.png",
            "width": 512,
            "height": 512
        },
        "screenshot": {
            "@type": "ImageObject", 
            "url": "https://your-domain.com/static/img/screenshot.png",
            "width": 1200,
            "height": 800
        },
        "applicationCategory": "BusinessApplication",
        "applicationSubCategory": "数据可视化工具",
        "operatingSystem": "跨平台Web应用",
        "browserRequirements": "现代浏览器 (Chrome 90+, Firefox 88+, Safari 14+, Edge 90+)",
        "memoryRequirements": "512MB RAM",
        "storageRequirements": "无需本地存储",
        "processorRequirements": "任何现代处理器",
        "offers": {
            "@type": "Offer",
            "price": "0",
            "priceCurrency": "CNY",
            "availability": "https://schema.org/InStock",
            "priceValidUntil": "2025-12-31",
            "description": "完全免费使用，无任何隐藏费用"
        },
        "featureList": [
            "在线文件上传 (无需下载软件)",
            "CSV/Excel/JSON文件支持",
            "一键生成专业图表",
            "多种图表类型 (折线图、柱状图、饼图等)",
            "实时数据清洗功能",
            "统计分析工具",
            "交互式仪表板",
            "数据导出功能",
            "历史数据缓存",
            "中英文界面",
            "全屏大屏展示",
            "移动端适配"
        ],
        "creator": {
            "@type": "Organization",
            "name": "xlcig Team",
            "url": "https://your-domain.com",
            "logo": "https://your-domain.com/static/img/logo.png"
        },
        "publisher": {
            "@type": "Organization", 
            "name": "xlcig Team",
            "logo": {
                "@type": "ImageObject",
                "url": "https://your-domain.com/static/img/logo.png"
            }
        },
        "inLanguage": ["zh-CN", "en-US"],
        "isAccessibleForFree": true,
        "usageInfo": "https://your-domain.com/help",
        "softwareRequirements": "现代Web浏览器",
        "accessibilityFeature": [
            "键盘导航支持",
            "屏幕阅读器兼容",
            "高对比度模式",
            "可调节字体大小"
        ],
        "accessibilityControl": [
            "fullKeyboardControl",
            "fullMouseControl", 
            "fullTouchControl"
        ],
        "accessibilityHazard": "none",
        "accessibilityAPI": "ARIA",
        "accessibilitySummary": "完全支持无障碍访问，兼容各种辅助技术",
        "aggregateRating": {
            "@type": "AggregateRating",
            "ratingValue": "4.9",
            "ratingCount": "2680",
            "bestRating": "5",
            "worstRating": "1",
            "reviewCount": "892"
        },
        "review": {
            "@type": "Review",
            "reviewRating": {
                "@type": "Rating",
                "ratingValue": "5",
                "bestRating": "5"
            },
            "author": {
                "@type": "Person",
                "name": "数据分析师张先生"
            },
            "reviewBody": "非常好用的在线数据可视化工具！无需下载安装，直接在浏览器中就能生成专业的图表。界面简洁，功能强大，完全免费，强烈推荐！"
        },
        "installUrl": "https://your-domain.com",
        "downloadUrl": "https://your-domain.com",
        "softwareVersion": "2.0",
        "dateCreated": "2024-01-01",
        "dateModified": "2024-01-15",
        "datePublished": "2024-01-01"
    }
    </script>
    
    <!-- FAQ Structured Data -->
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": [
            {
                "@type": "Question",
                "name": "xlcig Notebook需要下载安装吗？",
                "acceptedAnswer": {
                    "@type": "Answer",
                    "text": "不需要！xlcig Notebook是完全基于Web的在线数据可视化平台，您只需要现代浏览器即可使用，无需下载安装任何软件。"
                }
            },
            {
                "@type": "Question", 
                "name": "支持哪些文件格式？",
                "acceptedAnswer": {
                    "@type": "Answer",
                    "text": "支持CSV、Excel(.xlsx/.xls)、JSON等多种常见数据格式。您可以直接上传这些文件并立即开始可视化分析。"
                }
            },
            {
                "@type": "Question",
                "name": "xlcig Notebook是否完全免费？",
                "acceptedAnswer": {
                    "@type": "Answer",
                    "text": "是的！xlcig Notebook提供完全免费的在线数据可视化服务，包括图表生成、数据分析、仪表板制作等所有核心功能都免费使用。"
                }
            },
            {
                "@type": "Question",
                "name": "生成的图表可以导出吗？",
                "acceptedAnswer": {
                    "@type": "Answer",
                    "text": "当然可以！您可以将生成的图表导出为图片格式，或者将处理后的数据导出为CSV、Excel、JSON等格式。"
                }
            }
        ]
    }
    </script>
    
    <!-- Critical CSS inlined, non-critical CSS loaded async -->
    <style>
        /* Critical CSS for above-the-fold content */
        body { margin: 0; font-family: 'Segoe UI', sans-serif; }
        .header { background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%); color: white; padding: 1rem 2rem; }
        .loading-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.9); z-index: 9999; display: flex; align-items: center; justify-content: center; }
    </style>
    
    <!-- Stylesheets -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
    
    <!-- Structured Data -->
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "SoftwareApplication",
        "name": "xlcig Notebook Enterprise Analytics",
        "description": "Professional data visualization and analytics platform for enterprises",
        "url": "",
        "applicationCategory": "BusinessApplication",
        "operatingSystem": "Web Browser",
        "offers": {
            "@type": "Offer",
            "price": "0",
            "priceCurrency": "USD"
        },
        "creator": {
            "@type": "Organization",
            "name": "xlcig Team",
            "url": ""
        }
    }
    </script>
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --success-color: #27ae60;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --light-bg: #f8f9fa;
            --white: #ffffff;
            --border-color: #dee2e6;
            --text-color: #2c3e50;
            --muted-color: #6c757d;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
            background-color: var(--light-bg);
            color: var(--text-color);
            line-height: 1.6;
        }

        /* Header */
        .header {
            background: linear-gradient(135deg, var(--primary-color) 0%, #34495e 100%);
            color: var(--white);
            padding: 1rem 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: relative;
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1400px;
            margin: 0 auto;
        }

        .header-brand {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .brand-logo {
            width: 48px;
            height: 48px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        }

        .header h1 {
            font-size: 1.5rem;
            font-weight: 600;
            margin: 0;
        }

        .header-actions {
            display: flex;
            gap: 1rem;
            align-items: center;
        }

        .btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 6px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-primary {
            background: var(--secondary-color);
            color: var(--white);
        }

        .btn-primary:hover {
            background: #2980b9;
            transform: translateY(-1px);
        }

        .btn-success {
            background: var(--success-color);
            color: var(--white);
        }

        .btn-outline {
            background: transparent;
            color: var(--white);
            border: 1px solid var(--white);
        }

        .btn-outline:hover {
            background: var(--white);
            color: var(--primary-color);
        }

        /* Main Layout */
        .main-container {
            display: flex;
            min-height: calc(100vh - 80px);
        }

        /* Sidebar */
        .sidebar {
            width: 300px;
            background: var(--white);
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            overflow-y: auto;
            z-index: 100;
        }

        .sidebar-section {
            padding: 1.5rem;
            border-bottom: 1px solid var(--border-color);
        }

        .sidebar-title {
            font-size: 1rem;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        /* File Upload */
        .upload-area {
            border: 2px dashed #bdc3c7;
            border-radius: 8px;
            padding: 1.5rem;
            text-align: center;
            background: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .upload-area:hover, .upload-area.dragover {
            border-color: var(--secondary-color);
            background: #e3f2fd;
        }

        .upload-icon {
            font-size: 2rem;
            color: var(--muted-color);
            margin-bottom: 0.5rem;
        }

        #fileInput {
            display: none;
        }

        /* File List */
        .file-list {
            margin-top: 1rem;
        }

        .file-item {
            background: #f8f9fa;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 0.5rem;
            margin-bottom: 0.5rem;
            font-size: 0.85rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* Chart Controls */
        .chart-controls {
            background: var(--white);
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            border: 1px solid var(--border-color);
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: var(--text-color);
        }

        .form-select, .form-input {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background: var(--white);
            color: var(--text-color);
        }

        .form-select:focus, .form-input:focus {
            outline: none;
            border-color: var(--secondary-color);
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        /* Status Display */
        .status-display {
            padding: 0.75rem;
            border-radius: 6px;
            font-size: 0.9rem;
            margin-top: 1rem;
        }

        .status-info {
            background: #e3f2fd;
            color: #1976d2;
            border-left: 4px solid #2196f3;
        }

        .status-success {
            background: #e8f5e8;
            color: #2e7d32;
            border-left: 4px solid #4caf50;
        }

        .status-error {
            background: #ffebee;
            color: #c62828;
            border-left: 4px solid #f44336;
        }

        .status-warning {
            background: #fff3e0;
            color: #ef6c00;
            border-left: 4px solid #ff9800;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            padding: 2rem;
            overflow-y: auto;
        }

        /* Tabs */
        .tab-container {
            margin-bottom: 2rem;
        }

        .tab-nav {
            display: flex;
            background: var(--white);
            border-radius: 8px 8px 0 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .tab-button {
            padding: 1rem 1.5rem;
            background: transparent;
            border: none;
            cursor: pointer;
            font-weight: 500;
            color: var(--muted-color);
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
        }

        .tab-button.active {
            color: var(--secondary-color);
            border-bottom-color: var(--secondary-color);
            background: var(--light-bg);
        }

        .tab-content {
            background: var(--white);
            border-radius: 0 0 8px 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            min-height: 400px;
        }

        .tab-pane {
            display: none;
            padding: 2rem;
        }

        .tab-pane.active {
            display: block;
        }

        /* Dashboard Grid */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
            gap: 1.5rem;
            margin-top: 1rem;
            align-items: start;
            justify-content: center;
        }

        /* Ensure consistent card heights */
        .dashboard-grid .chart-card {
            height: 500px;
            display: flex;
            flex-direction: column;
        }

        .dashboard-grid .chart-body {
            flex: 1;
            min-height: 350px;
        }

        .chart-card {
            background: var(--white);
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            overflow: hidden;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .chart-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }

        .chart-header {
            background: var(--light-bg);
            padding: 1rem;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chart-title {
            font-size: 1rem;
            font-weight: 600;
            color: var(--text-color);
        }

        .chart-actions {
            display: flex;
            gap: 0.5rem;
        }

        .chart-btn {
            background: none;
            border: none;
            color: var(--muted-color);
            cursor: pointer;
            padding: 0.25rem;
            border-radius: 4px;
            transition: all 0.2s ease;
        }

        .chart-btn:hover {
            background: var(--border-color);
            color: var(--text-color);
        }

        .chart-body {
            height: 400px;
            min-height: 350px;
            position: relative;
            padding: 10px;
        }

        .chart-container {
            width: 100%;
            height: 100%;
            min-height: 320px;
        }

        /* Full Screen Dashboard */
        .fullscreen-dashboard {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: #0c1426;
            z-index: 9999;
            display: none;
            padding: 2rem;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .fullscreen-dashboard.active {
            display: block;
            opacity: 1;
        }

        .fullscreen-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            color: white;
        }

        .fullscreen-title {
            font-size: 1.5rem;
            margin: 0;
        }

        .fullscreen-close {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s ease;
        }

        .fullscreen-close:hover {
            background: rgba(255,255,255,0.3);
        }

        .fullscreen-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 1rem;
            height: calc(100vh - 120px);
            overflow-y: auto;
        }

        .fullscreen-chart {
            background: #1a1a1a;
            border-radius: 8px;
            padding: 1rem;
            min-height: 300px;
        }

        .fullscreen-dashboard.active {
            display: block;
        }

        .fullscreen-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            color: var(--white);
        }

        .fullscreen-title {
            font-size: 2rem;
            font-weight: 300;
        }

        .fullscreen-close {
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            color: var(--white);
            padding: 0.5rem 1rem;
            border-radius: 6px;
            cursor: pointer;
        }

        .fullscreen-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(2, 1fr);
            gap: 1rem;
            height: calc(100vh - 120px);
        }

        .fullscreen-chart {
            background: rgba(255,255,255,0.05);
            border-radius: 8px;
            border: 1px solid rgba(255,255,255,0.1);
        }

        /* Loading Spinner */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--secondary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Data Summary Table */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: var(--white);
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .data-table th {
            background: var(--light-bg);
            color: var(--text-color);
            font-weight: 600;
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        .data-table td {
            padding: 0.75rem 1rem;
            border-bottom: 1px solid #f1f3f4;
            color: var(--muted-color);
        }

        .data-table tr:hover {
            background: var(--light-bg);
        }

        /* Responsive */
        @media (max-width: 768px) {
            .main-container {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                max-height: 300px;
            }
            
            .dashboard-grid {
                grid-template-columns: 1fr;
            }
            
            .fullscreen-grid {
                grid-template-columns: 1fr;
                grid-template-rows: repeat(6, 1fr);
            }
        }

        /* Welcome Screen */
        .welcome-screen {
            text-align: center;
            padding: 4rem 2rem;
            color: var(--muted-color);
        }

        .welcome-icon {
            font-size: 4rem;
            margin-bottom: 1rem;
            color: var(--secondary-color);
        }

        /* Language Switch */
        .language-switch {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            background: rgba(255,255,255,0.1);
            border-radius: 20px;
            padding: 0.25rem;
        }

        .lang-btn {
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            border: none;
            background: transparent;
            color: var(--white);
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.8rem;
        }

        .lang-btn.active {
            background: var(--white);
            color: var(--primary-color);
        }

        /* Drag and Drop */
        .sortable-ghost {
            opacity: 0.4;
        }

        .sortable-chosen {
            transform: rotate(5deg);
        }

        .sortable-drag {
            transform: rotate(10deg);
        }

        .chart-card.dragging {
            transform: rotate(5deg);
            opacity: 0.8;
            z-index: 1000;
        }

        .drag-handle {
            cursor: move;
            color: var(--muted-color);
            font-size: 0.8rem;
        }

        .drag-handle:hover {
            color: var(--secondary-color);
        }

        /* Delete confirmation */
        .delete-confirm {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: var(--white);
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            z-index: 10000;
            display: none;
        }

        .delete-confirm.show {
            display: block;
        }

        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0,0,0,0.5);
            z-index: 9999;
            display: none;
        }

        .overlay.show {
            display: block;
        }

        /* Fullscreen improvements */
        .fullscreen-dashboard {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: #0c1426;
            z-index: 9999;
            display: none;
            padding: 2rem;
        }

        .fullscreen-dashboard.active {
            display: block;
        }

        .fullscreen-close:hover {
            background: rgba(255,255,255,0.2);
        }

        /* Chart card enhancements */
        .chart-card {
            position: relative;
        }

        .chart-card:hover .chart-actions {
            opacity: 1;
        }

        .chart-actions {
            opacity: 0.7;
            transition: opacity 0.3s ease;
        }

        /* Dark Theme */
        body[data-theme="dark"] {
            background-color: #1a1a1a;
            color: #ffffff;
        }

        body[data-theme="dark"] .sidebar {
            background: #2d2d2d;
            color: #ffffff;
        }

        body[data-theme="dark"] .chart-card {
            background: #2d2d2d;
            color: #ffffff;
        }

        body[data-theme="dark"] .chart-header {
            background: #3d3d3d;
            border-bottom-color: #4d4d4d;
        }

        body[data-theme="dark"] .tab-content {
            background: #2d2d2d;
            color: #ffffff;
        }

        body[data-theme="dark"] .data-table {
            background: #2d2d2d;
            color: #ffffff;
        }

        body[data-theme="dark"] .data-table th {
            background: #3d3d3d;
            color: #ffffff;
        }

        body[data-theme="dark"] .form-select,
        body[data-theme="dark"] .form-input {
            background: #3d3d3d;
            color: #ffffff;
            border-color: #4d4d4d;
        }

        body[data-theme="dark"] .chart-controls {
            background: #3d3d3d;
            border-color: #4d4d4d;
        }

        body[data-theme="dark"] .btn-outline {
            background: transparent;
            color: #ffffff;
            border-color: #4d4d4d;
        }

        body[data-theme="dark"] .btn-outline:hover {
            background: #4d4d4d;
            color: #ffffff;
        }

        /* Floating History Panel Styles */
        .floating-history-panel {
            position: fixed;
            top: 100px;
            right: 20px;
            width: 350px;
            max-height: 600px;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
            z-index: 1000;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            resize: both;
            overflow: hidden;
            min-width: 280px;
            min-height: 200px;
        }

        .floating-history-panel.collapsed {
            width: 60px;
            max-height: 60px;
            border-radius: 50%;
        }

        .floating-history-panel.collapsed .floating-panel-content {
            display: none;
        }

        .floating-history-panel.collapsed .panel-title {
            display: none;
        }

        .floating-history-panel.collapsed .floating-panel-header {
            padding: 15px;
            justify-content: center;
            border-radius: 50%;
        }

        .floating-panel-header {
            background: var(--primary-color);
            color: white;
            padding: 12px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: move;
            border-radius: 12px 12px 0 0;
            user-select: none;
        }

        .panel-title {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 600;
            font-size: 0.9rem;
        }

        .history-count {
            font-size: 0.8rem;
            opacity: 0.8;
        }

        .panel-controls {
            display: flex;
            gap: 4px;
        }

        .panel-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.2s;
            font-size: 0.8rem;
        }

        .panel-btn:hover {
            background: rgba(255,255,255,0.3);
        }

        .floating-panel-content {
            padding: 16px;
            max-height: 520px;
            overflow-y: auto;
        }

        .floating-panel-actions {
            margin-bottom: 16px;
        }

        .floating-history-grid {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .floating-history-item {
            background: var(--bg-light);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 12px;
            transition: all 0.2s ease;
            cursor: pointer;
        }

        .floating-history-item:hover {
            border-color: var(--primary-color);
            background: var(--primary-color-light);
        }

        .floating-history-item.selected {
            border-color: var(--primary-color);
            background: var(--primary-color-light);
        }

        .floating-item-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 8px;
        }

        .floating-item-title {
            font-weight: 600;
            color: var(--text-primary);
            font-size: 0.85rem;
            line-height: 1.3;
            margin: 0;
        }

        .floating-item-date {
            font-size: 0.7rem;
            color: var(--text-secondary);
            white-space: nowrap;
        }

        .floating-item-info {
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
            margin-bottom: 8px;
        }

        .floating-info-tag {
            font-size: 0.7rem;
            padding: 2px 6px;
            background: var(--card-bg);
            border-radius: 10px;
            color: var(--text-secondary);
            border: 1px solid var(--border-color);
        }

        .floating-item-actions {
            display: flex;
            gap: 6px;
            justify-content: flex-end;
        }

        .floating-item-actions .btn {
            padding: 4px 8px;
            font-size: 0.7rem;
        }

        .no-floating-data-message {
            text-align: center;
            padding: 2rem 1rem;
            color: var(--text-secondary);
        }

        .no-floating-data-message i {
            font-size: 2rem;
            color: var(--text-light);
            margin-bottom: 0.5rem;
        }

        .no-floating-data-message p {
            margin: 0;
            font-size: 0.8rem;
        }

        /* Drag and Drop Styles */
        .floating-history-panel.dragging {
            transform: scale(1.02);
            box-shadow: 0 12px 40px rgba(0,0,0,0.2);
        }

        .floating-history-panel.dragging .floating-panel-header {
            background: var(--primary-color-dark);
        }

        /* Dark mode adjustments */
        body[data-theme="dark"] .floating-history-panel {
            background: var(--card-bg);
            border-color: var(--border-color);
        }

        body[data-theme="dark"] .floating-history-item {
            background: rgba(255,255,255,0.05);
        }

        body[data-theme="dark"] .floating-history-item:hover {
            background: rgba(74, 144, 226, 0.1);
        }

        /* Header Tools Dropdown */
        .header-tools {
            position: relative;
        }

        .dropdown {
            position: relative;
            display: inline-block;
        }

        .dropdown-btn {
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }

        .dropdown-btn:hover {
            background: rgba(255,255,255,0.2);
        }

        .dropdown-content {
            display: none;
            position: absolute;
            right: 0;
            top: 100%;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
            z-index: 1001;
            min-width: 400px;
            padding: 16px;
            margin-top: 8px;
        }

        .dropdown.active .dropdown-content {
            display: block;
        }

        .dropdown-section {
            margin-bottom: 16px;
        }

        .dropdown-section:last-child {
            margin-bottom: 0;
        }

        .dropdown-section h5 {
            margin: 0 0 8px 0;
            color: var(--primary-color);
            font-weight: 600;
            font-size: 0.9rem;
        }

        .dropdown-item {
            display: flex;
            gap: 8px;
            align-items: center;
            flex-wrap: wrap;
        }

        .form-select-sm {
            padding: 4px 8px;
            font-size: 0.8rem;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background: var(--card-bg);
            color: var(--text-primary);
            min-width: 120px;
        }

        .btn-sm {
            padding: 4px 12px;
            font-size: 0.8rem;
        }

        /* Data Table Styles */
        .data-visualization-table {
            margin-top: 20px;
            background: var(--card-bg);
            border-radius: 8px;
            border: 1px solid var(--border-color);
            overflow: hidden;
        }

        .table-header {
            background: var(--primary-color);
            color: white;
            padding: 12px 16px;
            font-weight: 600;
        }

        .table-content {
            padding: 16px;
            max-height: 400px;
            overflow-y: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th,
        .data-table td {
            padding: 8px 12px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
            font-size: 0.85rem;
        }

        .data-table th {
            background: var(--bg-light);
            font-weight: 600;
            color: var(--text-primary);
        }

        .data-table td {
            color: var(--text-secondary);
        }

        .data-table tr:hover {
            background: var(--bg-light);
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="header">
                  <div class="header-content">
              <div class="header-brand">
                 <img src="/static/img/logo.png" alt="xlcig Logo" class="brand-logo">
                  <h1><span data-i18n="app.title">xlcig Notebook 在线数据可视化</span></h1>
              </div>
            <div class="header-actions">
                <!-- Advanced Tools Dropdown -->
                <div class="header-tools" style="display: none;" id="headerToolsSection">
                    <div class="dropdown">
                        <button class="dropdown-btn" id="advancedToolsBtn">
                            <i class="fas fa-tools"></i>
                            <span data-i18n="advanced.tools">Advanced Tools</span>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content" id="advancedToolsDropdown">
                            <div class="dropdown-section">
                                <h5 data-i18n="advanced.data_cleaning">Data Cleaning</h5>
                                <div class="dropdown-item">
                                    <select id="cleaningDatasetHeader" class="form-select-sm">
                                        <option value="" data-i18n="advanced.select_dataset">Select Dataset</option>
                                    </select>
                                    <select id="cleaningOperationHeader" class="form-select-sm">
                                        <option value="remove_nulls" data-i18n="advanced.remove_nulls">Remove Nulls</option>
                                        <option value="fill_nulls" data-i18n="advanced.fill_nulls">Fill Nulls</option>
                                        <option value="remove_duplicates" data-i18n="advanced.remove_duplicates">Remove Duplicates</option>
                                        <option value="normalize" data-i18n="advanced.normalize">Normalize</option>
                                        <option value="outlier_removal" data-i18n="advanced.outlier_removal">Remove Outliers</option>
                                    </select>
                                    <button class="btn btn-sm btn-secondary" onclick="applyCleaningFromHeader()">
                                        <i class="fas fa-broom"></i> <span data-i18n="advanced.apply">Apply</span>
                                    </button>
                                </div>
                            </div>
                            <div class="dropdown-section">
                                <h5 data-i18n="advanced.statistics">Statistics</h5>
                                <div class="dropdown-item">
                                    <select id="statsDatasetHeader" class="form-select-sm">
                                        <option value="" data-i18n="advanced.select_dataset">Select Dataset</option>
                                    </select>
                                    <button class="btn btn-sm btn-info" onclick="generateStatsFromHeader()">
                                        <i class="fas fa-chart-bar"></i> <span data-i18n="advanced.generate">Generate</span>
                                    </button>
                                </div>
                            </div>
                            <div class="dropdown-section">
                                <h5 data-i18n="advanced.export">Export Data</h5>
                                <div class="dropdown-item">
                                    <select id="exportDatasetHeader" class="form-select-sm">
                                        <option value="" data-i18n="advanced.select_dataset">Select Dataset</option>
                                    </select>
                                    <select id="exportFormatHeader" class="form-select-sm">
                                        <option value="csv">CSV</option>
                                        <option value="excel">Excel</option>
                                        <option value="json">JSON</option>
                                    </select>
                                    <button class="btn btn-sm btn-success" onclick="exportDataFromHeader()">
                                        <i class="fas fa-download"></i> <span data-i18n="advanced.export">Export</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="language-switch">
                    <button class="lang-btn active" data-lang="en">EN</button>
                    <button class="lang-btn" data-lang="zh">中文</button>
                </div>
                <button id="dashboardBtn" class="btn btn-outline" style="display: none;">
                    <i class="fas fa-tv"></i> <span data-i18n="dashboard.button">Visualization Dashboard</span>
                </button>
                <button id="fullscreenBtn" class="btn btn-primary" style="display: none;">
                    <i class="fas fa-expand"></i> <span data-i18n="fullscreen.button">Full Screen</span>
                </button>
            </div>
        </div>
    </div>

    <!-- Loading Overlay -->
    <div id="loadingOverlay" class="loading-overlay">
        <div style="text-align: center;">
            <div class="loading" style="margin: 0 auto 1rem;"></div>
            <div>Loading xlcig Analytics...</div>
        </div>
    </div>

    <!-- Main Container -->
    <div class="main-container">
        <!-- Sidebar -->
        <div class="sidebar">
            <!-- File Upload Section -->
            <div class="sidebar-section">
                <h3 class="sidebar-title">
                    <i class="fas fa-upload"></i>
                    <span data-i18n="upload.title">Data Upload</span>
                </h3>
                
                <div class="upload-area" onclick="document.getElementById('fileInput').click()">
                    <div class="upload-icon">
                        <i class="fas fa-cloud-upload-alt"></i>
                    </div>
                    <div data-i18n="upload.click">Click to select files</div>
                    <small style="color: #6c757d;" data-i18n="upload.drag">or drag and drop files here</small>
                </div>
                
                <input type="file" id="fileInput" multiple accept=".csv,.xlsx,.xls,.ipynb">
                
                <div id="fileList" class="file-list" style="display: none;"></div>
                
                <button id="processBtn" class="btn btn-primary" style="width: 100%; margin-top: 1rem;" disabled>
                    <i class="fas fa-cogs"></i> <span data-i18n="upload.analyze">Analyze Data</span>
                </button>
                
                <div id="statusDisplay" class="status-display status-info" data-i18n="upload.ready">
                    Ready for file upload
                </div>
            </div>

            <!-- Chart Builder Section -->
            <div class="sidebar-section" id="chartBuilderSection" style="display: none;">
                <h3 class="sidebar-title">
                    <i class="fas fa-chart-bar"></i>
                    <span data-i18n="builder.title">Chart Builder</span>
                </h3>
                
                <div class="chart-controls">
                    <div class="form-group">
                        <label class="form-label" data-i18n="builder.dataset">Dataset</label>
                        <select id="datasetSelect" class="form-select">
                            <option value="" data-i18n="builder.select_dataset">Select Dataset</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" data-i18n="builder.chart_type">Chart Type</label>
                        <select id="chartTypeSelect" class="form-select">
                            <option value="" data-i18n="builder.select_chart_type">Select Chart Type</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" data-i18n="builder.x_axis">X Axis</label>
                        <select id="xAxisSelect" class="form-select">
                            <option value="" data-i18n="builder.select_column">Select Column</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" data-i18n="builder.y_axis">Y Axis</label>
                        <select id="yAxisSelect" class="form-select">
                            <option value="" data-i18n="builder.select_column">Select Column</option>
                        </select>
                    </div>
                    
                    <button id="generateChartBtn" class="btn btn-success" style="width: 100%;">
                        <i class="fas fa-plus"></i> <span data-i18n="builder.generate">Generate Chart</span>
                    </button>
                </div>
            </div>

            <!-- History Cache -->
            <div class="sidebar-section" id="historySection" style="display: none;">
                <h3 class="sidebar-title">
                    <i class="fas fa-history"></i>
                    <span data-i18n="history.title">History Cache</span>
                </h3>
                
                <div class="chart-controls">
                    <div class="form-group">
                        <label class="form-label" data-i18n="history.saved_datasets">Saved Datasets</label>
                        <select id="historyDatasetSelect" class="form-select">
                            <option value="" data-i18n="history.no_history">No history found</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <button id="loadHistoryBtn" class="btn btn-primary" style="width: 100%; margin-bottom: 0.5rem;" disabled>
                            <i class="fas fa-download"></i> <span data-i18n="history.load_dataset">Load Dataset</span>
                        </button>
                        <button id="clearHistoryBtn" class="btn btn-outline" style="width: 100%;">
                            <i class="fas fa-trash"></i> <span data-i18n="history.clear_all">Clear All History</span>
                        </button>
                    </div>
                    
                    <div id="historyInfo" class="status-display status-info" style="display: none;">
                        <small data-i18n="history.info">Datasets are automatically saved to browser storage</small>
                    </div>
                </div>
            </div>

            <!-- Advanced Features -->
            <div class="sidebar-section" id="advancedSection" style="display: none;">
                <h3 class="sidebar-title">
                    <i class="fas fa-cog"></i>
                    <span data-i18n="advanced.title">Advanced Features</span>
                </h3>
                
                <!-- Data Cleaning Panel -->
                <div class="chart-controls" style="margin-bottom: 1rem;">
                    <h4 style="font-size: 0.9rem; margin: 0 0 0.5rem 0; color: var(--text-color); border-bottom: 1px solid var(--border-color); padding-bottom: 0.25rem;">
                        <i class="fas fa-broom"></i> <span data-i18n="advanced.data_cleaning">Data Cleaning</span>
                    </h4>
                    <div class="form-group">
                        <select id="cleaningDataset" class="form-select">
                            <option value="" data-i18n="advanced.select_dataset">Select Dataset</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <select id="cleaningOperation" class="form-select">
                            <option value="remove_nulls" data-i18n="advanced.remove_nulls">Remove Null Values</option>
                            <option value="fill_nulls" data-i18n="advanced.fill_nulls">Fill Null Values</option>
                            <option value="remove_duplicates" data-i18n="advanced.remove_duplicates">Remove Duplicates</option>
                            <option value="normalize" data-i18n="advanced.normalize">Normalize Data</option>
                            <option value="outlier_removal" data-i18n="advanced.remove_outliers">Remove Outliers</option>
                        </select>
                    </div>
                    <button id="applyCleaningBtn" class="btn btn-secondary" style="width: 100%;">
                        <i class="fas fa-magic"></i> <span data-i18n="advanced.apply_cleaning">Apply Cleaning</span>
                    </button>
                </div>

                <!-- Statistical Analysis Panel -->
                <div class="chart-controls" style="margin-bottom: 1rem;">
                    <h4 style="font-size: 0.9rem; margin: 0 0 0.5rem 0; color: var(--text-color); border-bottom: 1px solid var(--border-color); padding-bottom: 0.25rem;">
                        <i class="fas fa-chart-line"></i> <span data-i18n="advanced.statistical_analysis">Statistical Analysis</span>
                    </h4>
                    <div class="form-group">
                        <select id="analysisDataset" class="form-select">
                            <option value="" data-i18n="advanced.select_dataset">Select Dataset</option>
                        </select>
                    </div>
                    <button id="generateStatsBtn" class="btn btn-info" style="width: 100%;">
                        <i class="fas fa-calculator"></i> <span data-i18n="advanced.generate_statistics">Generate Report</span>
                    </button>
                </div>

                <!-- Advanced Charts Panel -->
                <div class="chart-controls" style="margin-bottom: 1rem;">
                    <h4 style="font-size: 0.9rem; margin: 0 0 0.5rem 0; color: var(--text-color); border-bottom: 1px solid var(--border-color); padding-bottom: 0.25rem;">
                        <i class="fas fa-chart-area"></i> <span data-i18n="advanced.advanced_charts">Advanced Charts</span>
                    </h4>
                    <div class="form-group">
                        <select id="advancedChartDataset" class="form-select">
                            <option value="" data-i18n="advanced.select_dataset">Select Dataset</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <select id="advancedChartType" class="form-select">
                            <option value="correlation_matrix" data-i18n="advanced.correlation_matrix">Correlation Matrix</option>
                            <option value="box_plot" data-i18n="advanced.box_plot">Box Plot</option>
                            <option value="multi_line" data-i18n="advanced.multi_line">Multi-Line Chart</option>
                        </select>
                    </div>
                    <button id="generateAdvancedChartBtn" class="btn btn-primary" style="width: 100%;">
                        <i class="fas fa-plus-circle"></i> <span data-i18n="advanced.generate_chart">Generate Chart</span>
                    </button>
                </div>

                <!-- Export & Templates Panel -->
                <div class="chart-controls">
                    <h4 style="font-size: 0.9rem; margin: 0 0 0.5rem 0; color: var(--text-color); border-bottom: 1px solid var(--border-color); padding-bottom: 0.25rem;">
                        <i class="fas fa-download"></i> <span data-i18n="advanced.export_templates">Export & Templates</span>
                    </h4>
                    
                    <div class="form-group">
                        <select id="exportDataset" class="form-select">
                            <option value="" data-i18n="advanced.select_dataset">Select Dataset</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <select id="exportFormat" class="form-select">
                            <option value="csv">CSV</option>
                            <option value="excel">Excel (XLSX)</option>
                            <option value="json">JSON</option>
                        </select>
                    </div>
                    
                    <button id="exportDataBtnAdvanced" class="btn btn-success" style="width: 100%; margin-bottom: 0.5rem;">
                        <i class="fas fa-file-export"></i> <span data-i18n="advanced.export_data">Export Data</span>
                    </button>
                    
                    <div class="form-group">
                        <label class="form-label" data-i18n="advanced.theme">Theme</label>
                        <select id="themeSelect" class="form-select">
                            <option value="light" data-i18n="advanced.theme_light">Light</option>
                            <option value="dark" data-i18n="advanced.theme_dark">Dark</option>
                            <option value="auto" data-i18n="advanced.theme_auto">Auto</option>
                        </select>
                    </div>
                    
                    <button id="saveTemplateBtn" class="btn btn-outline" style="width: 100%; margin-bottom: 0.5rem;">
                        <i class="fas fa-save"></i> <span data-i18n="advanced.save_template">Save Template</span>
                    </button>
                    <button id="loadTemplateBtn" class="btn btn-outline" style="width: 100%;">
                        <i class="fas fa-folder-open"></i> <span data-i18n="advanced.load_template">Load Template</span>
                    </button>
                </div>
                
                <!-- Advertisement Space -->
                <div class="ad-space" style="margin-top: 1rem; padding: 1rem; background: #f8f9fa; border-radius: 6px; text-align: center; border: 1px solid #dee2e6;">
                    <small style="color: #6c757d;" data-i18n="ad.sponsored">Sponsored</small>
                    <div style="margin: 0.5rem 0; min-height: 80px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 4px; display: flex; align-items: center; justify-content: center; color: white; font-weight: 500;">
                        <span data-i18n="ad.placeholder">Your Ad Here</span>
                    </div>
                    <small style="color: #6c757d; font-size: 0.75rem;" data-i18n="ad.info">Support open source development</small>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Welcome Screen -->
            <div id="welcomeScreen" class="welcome-screen">
                <div class="welcome-icon">
                    <i class="fas fa-chart-area"></i>
                </div>
                <h2 data-i18n="welcome.title">Welcome to Free Online Data Visualization Platform</h2>
                <p data-i18n="welcome.description">Free online tool, no download required! Upload CSV, Excel files to generate professional charts instantly</p>
                
                <!-- SEO优化的特色说明 -->
                <div class="welcome-features">
                    <div class="feature-item">
                        <i class="fas fa-cloud-upload-alt"></i>
                        <span data-i18n="welcome.feature1">No Download Required</span>
                    </div>
                    <div class="feature-item">
                        <i class="fas fa-magic"></i>
                        <span data-i18n="welcome.feature2">One-Click Generation</span>
                    </div>
                    <div class="feature-item">
                        <i class="fas fa-free-code-camp"></i>
                        <span data-i18n="welcome.feature3">Completely Free</span>
                    </div>
                    <div class="feature-item">
                        <i class="fas fa-devices"></i>
                        <span data-i18n="welcome.feature4">All Devices Supported</span>
                    </div>
                </div>
            </div>

            <!-- Tab Container -->
            <div id="mainContent" class="tab-container" style="display: none;">
                <!-- Tab Navigation -->
                <div class="tab-nav">
                    <button class="tab-button active" data-tab="overview">
                        <i class="fas fa-table"></i> <span data-i18n="tabs.overview">Data Overview</span>
                    </button>
                    <button class="tab-button" data-tab="charts">
                        <i class="fas fa-chart-pie"></i> <span data-i18n="tabs.charts">Charts & Analysis</span>
                    </button>
                    <button class="tab-button" data-tab="builder">
                        <i class="fas fa-tools"></i> <span data-i18n="tabs.builder">Chart Builder</span>
                    </button>

                </div>

                <!-- Tab Content -->
                <div class="tab-content">
                    <!-- Data Overview Tab -->
                    <div id="overview-tab" class="tab-pane active">
                        <h3 data-i18n="overview.title">Dataset Overview</h3>
                        <div id="dataSummary">
                            <table id="summaryTable" class="data-table">
                                <thead>
                                    <tr>
                                        <th data-i18n="table.dataset_name">Dataset Name</th>
                                        <th data-i18n="table.rows">Rows</th>
                                        <th data-i18n="table.columns">Columns</th>
                                        <th data-i18n="table.numeric">Numeric</th>
                                        <th data-i18n="table.categorical">Categorical</th>
                                        <th data-i18n="table.size">Size</th>
                                    </tr>
                                </thead>
                                <tbody id="summaryTableBody">
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Charts Tab -->
                    <div id="charts-tab" class="tab-pane">
                        <h3 data-i18n="charts.title">Data Analysis Dashboard</h3>
                        <div id="chartsGrid" class="dashboard-grid">
                            <!-- Charts will be populated here -->
                        </div>
                    </div>

                    <!-- Chart Builder Tab -->
                    <div id="builder-tab" class="tab-pane">
                        <h3 data-i18n="builder.page_title">Custom Chart Builder</h3>
                        <div id="customChartsGrid" class="dashboard-grid">
                            <!-- Custom charts will be populated here -->
                        </div>
                        
                        <!-- Data Visualization Table -->
                        <div id="dataVisualizationTable" class="data-visualization-table" style="display: none;">
                            <div class="table-header">
                                <i class="fas fa-table"></i>
                                <span data-i18n="table.data_preview">Data Preview</span>
                                <span id="currentTableDataset" style="margin-left: 10px; opacity: 0.8;"></span>
                            </div>
                            <div class="table-content">
                                <div id="dataTableContainer">
                                    <!-- Data table will be populated here -->
                                </div>
                            </div>
                        </div>
                    </div>


                </div>
            </div>
        </div>
    </div>

    <!-- Floating History Panel -->
    <div id="floatingHistoryPanel" class="floating-history-panel">
        <div class="floating-panel-header">
            <div class="panel-title">
                <i class="fas fa-history"></i>
                <span data-i18n="history.title">History Cache</span>
                <span class="history-count" id="floatingHistoryCount">(0)</span>
            </div>
            <div class="panel-controls">
                <button id="toggleHistoryPanel" class="panel-btn" title="Toggle Panel">
                    <i class="fas fa-chevron-right"></i>
                </button>
                <button id="refreshFloatingHistory" class="panel-btn" title="Refresh">
                    <i class="fas fa-sync-alt"></i>
                </button>
            </div>
        </div>
        <div class="floating-panel-content">
            <div class="floating-panel-actions">
                <button id="clearAllFloatingHistory" class="btn btn-danger btn-sm" style="width: 100%;">
                    <i class="fas fa-trash"></i> <span data-i18n="history.clear_all">Clear All</span>
                </button>
            </div>
            <div id="floatingHistoryGrid" class="floating-history-grid">
                <!-- History items will be populated here -->
            </div>
            <div id="noFloatingHistoryMessage" class="no-floating-data-message" style="display: none;">
                <div class="no-data-content">
                    <i class="fas fa-history"></i>
                    <p data-i18n="history.no_history">No history found</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Full Screen Dashboard -->
    <div id="fullscreenDashboard" class="fullscreen-dashboard" style="display: none;">
        <div class="fullscreen-header">
            <h1 class="fullscreen-title" data-i18n="fullscreen.title">Data Visualization Dashboard</h1>
            <button class="fullscreen-close" onclick="safeExitFullscreen()">
                <i class="fas fa-times"></i> <span data-i18n="fullscreen.exit">Exit Fullscreen</span>
            </button>
        </div>
        <div id="fullscreenGrid" class="fullscreen-grid">
            <!-- Fullscreen charts will be populated here -->
        </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <div id="overlay" class="overlay"></div>
    <div id="deleteConfirm" class="delete-confirm">
        <h3 data-i18n="delete.title">Confirm Delete</h3>
        <p data-i18n="delete.message">Are you sure you want to delete this chart?</p>
        <div style="display: flex; gap: 1rem; justify-content: flex-end; margin-top: 1.5rem;">
            <button class="btn btn-outline" onclick="cancelDelete()">
                <span data-i18n="delete.cancel">Cancel</span>
            </button>
            <button class="btn btn-danger" onclick="confirmDelete()" style="background: var(--danger-color);">
                <span data-i18n="delete.confirm">Delete</span>
            </button>
        </div>
    </div>

    <script>
        // Global variables
        let selectedFiles = [];
        let currentSessionId = null;
        let sessionData = null;
        let customCharts = [];
        let currentLanguage = 'en';
        let sortableInstance = null;
        let pendingDeleteChart = null;
        let isProcessing = false;  // Add processing state flag
        let historyCache = [];     // Local history cache

        // Internationalization
        const i18n = {
            en: {
                'app.title': 'xlcig Notebook Online Data Visualization',
                'dashboard.button': 'Visualization Dashboard',
                'fullscreen.button': 'Full Screen',
                'upload.title': 'Data Upload',
                'upload.click': 'Click to select files',
                'upload.drag': 'or drag and drop files here',
                'upload.analyze': 'Analyze Data',
                'upload.ready': 'Ready for file upload',
                'upload.processing': 'Processing files, please wait...',
                'upload.success': 'Successfully processed {0} datasets',
                'upload.error': 'Error: {0}',
                'upload.reanalyze': 'Re-analyze Data',
                'upload.analysis_complete': 'Analysis completed successfully',
                'upload.session_expired': 'Session expired, re-uploading data...',
                'upload.select_files': 'Please select files first',
                'upload.processing_wait': 'Processing in progress, please wait...',
                'builder.title': 'Chart Builder',
                'builder.dataset': 'Dataset',
                'builder.select_dataset': 'Select Dataset',
                'builder.chart_type': 'Chart Type',
                'builder.select_chart_type': 'Select Chart Type',
                'builder.x_axis': 'X Axis',
                'builder.y_axis': 'Y Axis',
                'builder.select_column': 'Select Column',
                'builder.generate': 'Generate Chart',
                'builder.generating': 'Generating',
                'builder.page_title': 'Custom Chart Builder',
                'tabs.overview': 'Data Overview',
                'tabs.charts': 'Charts & Analysis',
                'tabs.builder': 'Chart Builder',
                'overview.title': 'Dataset Overview',
                'charts.title': 'Data Analysis Dashboard',
                'table.dataset_name': 'Dataset Name',
                'table.rows': 'Rows',
                'table.columns': 'Columns',
                'table.numeric': 'Numeric',
                'table.categorical': 'Categorical',
                'table.size': 'Size',
                'welcome.title': 'Welcome to Free Online Data Visualization Platform',
                'welcome.title': 'Welcome to Free Online Data Visualization Platform',
                'welcome.description': 'Free online tool, no download required! Upload CSV, Excel files to generate professional charts instantly',
                'welcome.feature1': 'No Download Required',
                'welcome.feature2': 'One-Click Generation',
                'welcome.feature3': 'Completely Free',
                'welcome.feature4': 'All Devices Supported',
                'fullscreen.title': 'Data Visualization Dashboard',
                'fullscreen.exit': 'Exit Fullscreen',
                'fullscreen.no_charts': 'No charts available for fullscreen display',
                'fullscreen.upload_hint': 'Please upload data and generate charts first',
                'history.title': 'History Cache',
                'history.saved_datasets': 'Saved Datasets',
                'history.no_history': 'No history found',
                'history.select_dataset': 'Select a dataset',
                'history.load_dataset': 'Load Dataset',
                'history.clear_all': 'Clear All History',
                'history.info': 'Datasets are automatically saved to browser storage',
                'history.select_dataset_first': 'Please select a dataset first',
                'history.dataset_not_found': 'Selected dataset not found',
                'history.loaded_successfully': 'Dataset loaded successfully',
                'history.load_failed': 'Failed to load dataset from history',
                'history.loading': 'Loading dataset from history...',
                'history.loaded_from_cache': 'Dataset loaded from cache. Upload files again for full analysis.',
                'history.confirm_clear': 'Are you sure you want to clear all history? This cannot be undone.',
                'history.cleared': 'History cleared successfully',
                'history.clear_failed': 'Failed to clear history',
                'history.just_now': 'just now',
                'history.mins_ago': ' mins ago',
                'history.hours_ago': ' hours ago',
                'history.days_ago': ' days ago',
                'tabs.history': 'History Data',
                'history.page_title': 'Historical Datasets',
                'history.total_datasets': 'Total Datasets',
                'history.refresh': 'Refresh',
                'history.no_data_title': 'No Historical Data',
                'history.no_data_desc': 'Upload datasets to see them appear here',
                'history.files': 'files',
                'history.rows': 'rows',
                'history.columns': 'columns',
                'history.visualize': 'Visualize',
                'history.delete': 'Delete',
                'history.confirm_delete': 'Are you sure you want to delete this dataset from history?',
                'history.deleted': 'Dataset deleted from history',
                'history.delete_failed': 'Failed to delete dataset from history',
                'advanced.tools': 'Advanced Tools',
                'advanced.data_cleaning': 'Data Cleaning',
                'advanced.statistics': 'Statistics',
                'advanced.export': 'Export Data',
                'advanced.select_dataset': 'Select Dataset',
                'advanced.remove_nulls': 'Remove Nulls',
                'advanced.fill_nulls': 'Fill Nulls',
                'advanced.remove_duplicates': 'Remove Duplicates',
                'advanced.normalize': 'Normalize',
                'advanced.outlier_removal': 'Remove Outliers',
                'advanced.apply': 'Apply',
                'advanced.generate': 'Generate',
                'table.data_preview': 'Data Preview',
                'alert.select_dataset_operation': 'Please select dataset and operation',
                'alert.cleaning_success': 'Cleaning successful',
                'alert.cleaning_error': 'Cleaning error',
                'alert.stats_error': 'Statistics error',
                'alert.export_success': 'Export successful',
                'alert.export_error': 'Export error',
                'alert.network_error': 'Network error',
                'delete.title': 'Confirm Delete',
                'delete.message': 'Are you sure you want to delete this chart?',
                'delete.cancel': 'Cancel',
                'delete.confirm': 'Delete',
                'alert.select_dataset_chart': 'Please select dataset and chart type',
                'alert.chart_generation_error': 'Error generating chart',
                'alert.export_error': 'Error exporting data',
                'alert.download_error': 'Error downloading chart',
                'alert.link_copied': 'Share link copied to clipboard!',
                'alert.template_saved': 'Template saved successfully!',
                'alert.save_error': 'Error saving template',
                'alert.no_templates': 'No templates found',
                'alert.select_template': 'Select a template:',
                'alert.enter_template_number': 'Enter template number:',
                'alert.template_loaded': 'Template loaded successfully!',
                'alert.load_error': 'Error loading template',
                'alert.select_dataset': 'Please select a dataset',
                'alert.select_dataset_operation': 'Please select dataset and operation',
                'alert.select_dataset_chart_type': 'Please select dataset and chart type',
                'alert.cleaning_success': 'Data cleaning completed',
                'alert.cleaning_error': 'Data cleaning failed',
                'alert.stats_error': 'Statistical analysis failed',
                'alert.export_success': 'Data exported successfully',
                'alert.chart_generated': 'Chart generated successfully',
                'alert.chart_error': 'Chart generation failed',
                'alert.network_error': 'Network error occurred',
                'stats.title': 'Statistical Analysis Report',
                'stats.basic_info': 'Basic Information',
                'stats.total_rows': 'Total Rows',
                'stats.total_columns': 'Total Columns',
                'stats.memory_usage': 'Memory Usage',
                'stats.null_values': 'Null Values',
                'stats.duplicate_rows': 'Duplicate Rows',
                'stats.column_types': 'Column Types',
                'stats.numeric': 'Numeric',
                'stats.categorical': 'Categorical',
                'stats.datetime': 'DateTime',
                'stats.missing_data': 'Missing Data Analysis',
                'chart.drag_to_reorder': 'Drag to reorder',
                'chart.duplicate': 'Duplicate',
                'chart.edit': 'Edit',
                'chart.delete': 'Delete',
                'chart.download': 'Download as PNG',
                'chart.share': 'Share Chart',
                'chart.fullscreen': 'Fullscreen',
                'chart_types.line': 'Line Chart',
                'chart_types.bar': 'Bar Chart',
                'chart_types.scatter': 'Scatter Plot',
                'chart_types.pie': 'Pie Chart',
                'chart_types.heatmap': 'Heatmap',
                'chart_types.histogram': 'Histogram',
                'chart_types.box': 'Box Plot',
                'chart_types.radar': 'Radar Chart',
                'chart_types.funnel': 'Funnel Chart',
                'advanced.title': 'Advanced Features',
                'advanced.theme': 'Theme',
                'advanced.theme_light': 'Light',
                'advanced.theme_dark': 'Dark',
                'advanced.theme_auto': 'Auto',
                'advanced.export': 'Export Data',
                'advanced.export_csv': 'Export as CSV',
                'advanced.templates': 'Dashboard Templates',
                'advanced.save_template': 'Save Template',
                'advanced.load_template': 'Load Template',
                'advanced.data_cleaning': 'Data Cleaning',
                'advanced.statistical_analysis': 'Statistical Analysis',
                'advanced.advanced_charts': 'Advanced Charts',
                'advanced.export_templates': 'Export & Templates',
                'advanced.select_dataset': 'Select Dataset',
                'advanced.remove_nulls': 'Remove Null Values',
                'advanced.fill_nulls': 'Fill Null Values',
                'advanced.remove_duplicates': 'Remove Duplicates',
                'advanced.normalize': 'Normalize Data',
                'advanced.remove_outliers': 'Remove Outliers',
                'advanced.apply_cleaning': 'Apply Cleaning',
                'advanced.generate_statistics': 'Generate Report',
                'advanced.correlation_matrix': 'Correlation Matrix',
                'advanced.box_plot': 'Box Plot',
                'advanced.multi_line': 'Multi-Line Chart',
                'advanced.generate_chart': 'Generate Chart',
                'advanced.export_data': 'Export Data',
                'ad.sponsored': 'Sponsored',
                'ad.placeholder': 'Your Ad Here',
                'ad.info': 'Support open source development',
                // SEO Content
                'seo.title': 'xlcig Notebook - Free Online Data Visualization Platform | No Download Required',
                'seo.description': 'Free online data visualization tool! No download required. Upload CSV, Excel files and generate professional charts instantly in your browser. Enterprise-grade analytics platform.',
                'seo.keywords': 'free online data visualization, no download chart generator, web-based analytics, instant charts, CSV visualization, Excel analysis, browser tool, free data analysis'
            },
            zh: {
                'app.title': 'xlcig Notebook 在线数据可视化',
                'dashboard.button': '可视化仪表板',
                'fullscreen.button': '全屏模式',
                'upload.title': '数据上传',
                'upload.click': '点击选择文件',
                'upload.drag': '或拖拽文件到此处',
                'upload.analyze': '分析数据',
                'upload.ready': '准备上传文件',
                'upload.processing': '正在处理文件，请稍候...',
                'upload.success': '成功处理了 {0} 个数据集',
                'upload.error': '错误: {0}',
                'upload.reanalyze': '重新分析数据',
                'upload.analysis_complete': '分析完成',
                'upload.session_expired': '会话已过期，正在重新上传数据...',
                'upload.select_files': '请先选择文件',
                'upload.processing_wait': '正在处理中，请稍候...',
                'builder.title': '图表构建器',
                'builder.dataset': '数据集',
                'builder.select_dataset': '选择数据集',
                'builder.chart_type': '图表类型',
                'builder.select_chart_type': '选择图表类型',
                'builder.x_axis': 'X 轴',
                'builder.y_axis': 'Y 轴',
                'builder.select_column': '选择列',
                'builder.generate': '生成图表',
                'builder.generating': '生成中',
                'builder.page_title': '自定义图表构建器',
                'tabs.overview': '数据概览',
                'tabs.charts': '图表分析',
                'tabs.builder': '图表构建器',
                'overview.title': '数据集概览',
                'charts.title': '数据分析仪表板',
                'table.dataset_name': '数据集名称',
                'table.rows': '行数',
                'table.columns': '列数',
                'table.numeric': '数值列',
                'table.categorical': '分类列',
                'table.size': '大小',
                'welcome.title': '欢迎使用在线数据可视化平台',
                'welcome.description': '免费在线工具，无需下载！上传CSV、Excel文件即可一键生成专业图表',
                'welcome.feature1': '无需下载安装',
                'welcome.feature2': '一键在线生成',
                'welcome.feature3': '完全免费使用',
                'welcome.feature4': '支持所有设备',
                'fullscreen.title': '数据可视化大屏',
                'fullscreen.exit': '退出全屏',
                'fullscreen.no_charts': '暂无图表可供全屏显示',
                'fullscreen.upload_hint': '请先上传数据并生成图表',
                'history.title': '历史缓存',
                'history.saved_datasets': '已保存数据集',
                'history.no_history': '暂无历史记录',
                'history.select_dataset': '选择数据集',
                'history.load_dataset': '加载数据集',
                'history.clear_all': '清空所有历史',
                'history.info': '数据集会自动保存到浏览器存储',
                'history.select_dataset_first': '请先选择一个数据集',
                'history.dataset_not_found': '未找到选中的数据集',
                'history.loaded_successfully': '数据集加载成功',
                'history.load_failed': '从历史记录加载数据集失败',
                'history.loading': '正在从历史记录加载数据集...',
                'history.loaded_from_cache': '已从缓存加载数据集。重新上传文件以获得完整分析功能。',
                'history.confirm_clear': '确定要清空所有历史记录吗？此操作无法撤销。',
                'history.cleared': '历史记录已清空',
                'history.clear_failed': '清空历史记录失败',
                'history.just_now': '刚刚',
                'history.mins_ago': ' 分钟前',
                'history.hours_ago': ' 小时前',
                'history.days_ago': ' 天前',
                'tabs.history': '历史数据',
                'history.page_title': '历史数据集',
                'history.total_datasets': '数据集总数',
                'history.refresh': '刷新',
                'history.no_data_title': '暂无历史数据',
                'history.no_data_desc': '上传数据集后会在这里显示',
                'history.files': '个文件',
                'history.rows': '行',
                'history.columns': '列',
                'history.visualize': '可视化',
                'history.delete': '删除',
                'history.confirm_delete': '确定要从历史记录中删除这个数据集吗？',
                'history.deleted': '数据集已从历史记录中删除',
                'history.delete_failed': '删除数据集失败',
                'advanced.tools': '高级工具',
                'advanced.data_cleaning': '数据清洗',
                'advanced.statistics': '统计分析',
                'advanced.export': '数据导出',
                'advanced.select_dataset': '选择数据集',
                'advanced.remove_nulls': '删除空值',
                'advanced.fill_nulls': '填充空值',
                'advanced.remove_duplicates': '删除重复值',
                'advanced.normalize': '数据标准化',
                'advanced.outlier_removal': '删除异常值',
                'advanced.apply': '应用',
                'advanced.generate': '生成',
                'table.data_preview': '数据预览',
                'alert.select_dataset_operation': '请选择数据集和操作',
                'alert.cleaning_success': '清洗成功',
                'alert.cleaning_error': '清洗错误',
                'alert.stats_error': '统计错误',
                'alert.export_success': '导出成功',
                'alert.export_error': '导出错误',
                'alert.network_error': '网络错误',
                'delete.title': '确认删除',
                'delete.message': '您确定要删除这个图表吗？',
                'delete.cancel': '取消',
                'delete.confirm': '删除',
                'alert.select_dataset_chart': '请选择数据集和图表类型',
                'alert.chart_generation_error': '生成图表时出错',
                'alert.export_error': '导出数据时出错',
                'alert.download_error': '下载图表时出错',
                'alert.link_copied': '分享链接已复制到剪贴板！',
                'alert.template_saved': '模板保存成功！',
                'alert.save_error': '保存模板时出错',
                'alert.no_templates': '未找到模板',
                'alert.select_template': '选择模板：',
                'alert.enter_template_number': '输入模板编号：',
                'alert.template_loaded': '模板加载成功！',
                'alert.load_error': '加载模板时出错',
                'alert.select_dataset': '请选择数据集',
                'alert.select_dataset_operation': '请选择数据集和操作',
                'alert.select_dataset_chart_type': '请选择数据集和图表类型',
                'alert.cleaning_success': '数据清洗完成',
                'alert.cleaning_error': '数据清洗失败',
                'alert.stats_error': '统计分析失败',
                'alert.export_success': '数据导出成功',
                'alert.chart_generated': '图表生成成功',
                'alert.chart_error': '图表生成失败',
                'alert.network_error': '网络错误',
                'stats.title': '统计分析报告',
                'stats.basic_info': '基本信息',
                'stats.total_rows': '总行数',
                'stats.total_columns': '总列数',
                'stats.memory_usage': '内存使用',
                'stats.null_values': '空值数量',
                'stats.duplicate_rows': '重复行数',
                'stats.column_types': '列类型',
                'stats.numeric': '数值型',
                'stats.categorical': '分类型',
                'stats.datetime': '日期时间',
                'stats.missing_data': '缺失数据分析',
                'chart.drag_to_reorder': '拖拽重新排序',
                'chart.duplicate': '复制',
                'chart.edit': '编辑',
                'chart.delete': '删除',
                'chart.download': '下载为PNG',
                'chart.share': '分享图表',
                'chart.fullscreen': '全屏显示',
                'chart_types.line': '折线图',
                'chart_types.bar': '柱状图',
                'chart_types.scatter': '散点图',
                'chart_types.pie': '饼图',
                'chart_types.heatmap': '热力图',
                'chart_types.histogram': '直方图',
                'chart_types.box': '箱线图',
                'chart_types.radar': '雷达图',
                'chart_types.funnel': '漏斗图',
                'advanced.title': '高级功能',
                'advanced.theme': '主题',
                'advanced.theme_light': '浅色',
                'advanced.theme_dark': '深色',
                'advanced.theme_auto': '自动',
                'advanced.export': '导出数据',
                'advanced.export_csv': '导出为CSV',
                'advanced.templates': '仪表板模板',
                'advanced.save_template': '保存模板',
                'advanced.load_template': '加载模板',
                'advanced.data_cleaning': '数据清洗',
                'advanced.statistical_analysis': '统计分析',
                'advanced.advanced_charts': '高级图表',
                'advanced.export_templates': '导出与模板',
                'advanced.select_dataset': '选择数据集',
                'advanced.remove_nulls': '删除空值',
                'advanced.fill_nulls': '填补空值',
                'advanced.remove_duplicates': '删除重复项',
                'advanced.normalize': '数据标准化',
                'advanced.remove_outliers': '删除异常值',
                'advanced.apply_cleaning': '应用清洗',
                'advanced.generate_statistics': '生成报告',
                'advanced.correlation_matrix': '相关性矩阵',
                'advanced.box_plot': '箱线图',
                'advanced.multi_line': '多线图',
                'advanced.generate_chart': '生成图表',
                'advanced.export_data': '导出数据',
                'ad.sponsored': '赞助商',
                'ad.placeholder': '广告位招租',
                'ad.info': '支持开源项目发展',
                // SEO Content
                'seo.title': 'xlcig Notebook 企业数据分析平台',
                'seo.description': '专业的数据可视化分析平台。支持CSV、Excel文件上传，创建交互式图表，构建企业级数据仪表板，AI智能洞察。',
                'seo.keywords': '数据可视化, 数据分析平台, 商业智能, 仪表板, 图表, 数据分析, CSV, Excel, 企业分析'
            }
        };

        // DOM elements
        const fileInput = document.getElementById('fileInput');
        const fileList = document.getElementById('fileList');
        const processBtn = document.getElementById('processBtn');
        const statusDisplay = document.getElementById('statusDisplay');
        const uploadArea = document.querySelector('.upload-area');
        const welcomeScreen = document.getElementById('welcomeScreen');
        const mainContent = document.getElementById('mainContent');

        // Chart builder elements
        const chartBuilderSection = document.getElementById('chartBuilderSection');
        const datasetSelect = document.getElementById('datasetSelect');
        const chartTypeSelect = document.getElementById('chartTypeSelect');
        const xAxisSelect = document.getElementById('xAxisSelect');
        const yAxisSelect = document.getElementById('yAxisSelect');
        const generateChartBtn = document.getElementById('generateChartBtn');

                    // Initialize on page load
            initializeApp();
            
            // Load history on startup
            updateHistoryList();
            refreshFloatingHistoryGrid();

        function initializeApp() {
            // Set initial URLs for SEO
            initializeSEO();
            
            // Set initial language
            updateLanguage(currentLanguage);
            
            // Initialize event handlers
            initializeEventHandlers();
            
            // Setup sortable for charts grid
            setupSortable();
            
            // Hide loading overlay
            hideLoadingOverlay();
            
            // Send performance metrics
            sendPerformanceMetrics();
        }

        function hideLoadingOverlay() {
            const overlay = document.getElementById('loadingOverlay');
            if (overlay) {
                overlay.style.opacity = '0';
                setTimeout(() => {
                    overlay.style.display = 'none';
                }, 300);
            }
        }

        // Loading state management functions
        function showLoading() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            if (loadingOverlay) {
                loadingOverlay.style.display = 'flex';
                loadingOverlay.style.opacity = '1';
            }
        }

        function hideLoading() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            if (loadingOverlay) {
                loadingOverlay.style.opacity = '0';
                setTimeout(() => {
                    loadingOverlay.style.display = 'none';
                }, 300);
            }
        }

        function sendPerformanceMetrics() {
            // Monitor Core Web Vitals for SEO
            if ('performance' in window && 'PerformanceObserver' in window) {
                try {
                    // Largest Contentful Paint
                    new PerformanceObserver((entryList) => {
                        const entries = entryList.getEntries();
                        const lastEntry = entries[entries.length - 1];
                        console.log('LCP:', lastEntry.startTime);
                    }).observe({entryTypes: ['largest-contentful-paint']});

                    // First Input Delay
                    new PerformanceObserver((entryList) => {
                        const firstInput = entryList.getEntries()[0];
                        console.log('FID:', firstInput.processingStart - firstInput.startTime);
                    }).observe({entryTypes: ['first-input']});

                    // Cumulative Layout Shift
                    let clsValue = 0;
                    new PerformanceObserver((entryList) => {
                        for (const entry of entryList.getEntries()) {
                            if (!entry.hadRecentInput) {
                                clsValue += entry.value;
                            }
                        }
                        console.log('CLS:', clsValue);
                    }).observe({entryTypes: ['layout-shift']});
                } catch (e) {
                    console.log('Performance monitoring not supported');
                }
            }
        }

        function initializeSEO() {
            const currentUrl = window.location.href;
            
            // Update URL meta tags
            const ogUrl = document.getElementById('og-url');
            if (ogUrl) ogUrl.setAttribute('content', currentUrl);
            
            const twitterUrl = document.getElementById('twitter-url');
            if (twitterUrl) twitterUrl.setAttribute('content', currentUrl);
            
            // Update canonical URL if needed
            let canonical = document.querySelector('link[rel="canonical"]');
            if (!canonical) {
                canonical = document.createElement('link');
                canonical.rel = 'canonical';
                canonical.href = currentUrl;
                document.head.appendChild(canonical);
            }
        }

        function initializeEventHandlers() {
            // Language switcher
            document.querySelectorAll('.lang-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const lang = this.dataset.lang;
                    switchLanguage(lang);
                });
            });

            // File input change handler
            fileInput.addEventListener('change', function(e) {
                handleFileSelection(e.target.files);
            });

            // Drag and drop handlers
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });

            uploadArea.addEventListener('dragleave', function(e) {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
            });

            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
                handleFileSelection(e.dataTransfer.files);
            });

            // Process button handler
            processBtn.addEventListener('click', handleAnalyzeClick);

            // Tab navigation
            document.querySelectorAll('.tab-button').forEach(button => {
                button.addEventListener('click', function() {
                    switchTab(this.dataset.tab);
                });
            });

            // Chart builder handlers - with null checks
            if (datasetSelect) datasetSelect.addEventListener('change', onDatasetChange);
            if (chartTypeSelect) chartTypeSelect.addEventListener('change', onChartTypeChange);
            if (generateChartBtn) generateChartBtn.addEventListener('click', generateCustomChart);

            // Dashboard buttons - with null checks
            const dashboardBtn = document.getElementById('dashboardBtn');
            const fullscreenBtn = document.getElementById('fullscreenBtn');
            if (dashboardBtn) dashboardBtn.addEventListener('click', showDashboard);
            if (fullscreenBtn) fullscreenBtn.addEventListener('click', safeEnterFullscreen);

            // Advanced features handlers - with null checks
            const themeSelect = document.getElementById('themeSelect');
            const exportDataBtn = document.getElementById('exportDataBtn');
            const saveTemplateBtn = document.getElementById('saveTemplateBtn');
            const loadTemplateBtn = document.getElementById('loadTemplateBtn');
            const applyCleaningBtn = document.getElementById('applyCleaningBtn');
            const generateStatsBtn = document.getElementById('generateStatsBtn');
            const exportDataBtnAdvanced = document.getElementById('exportDataBtnAdvanced');
            const generateAdvancedChartBtn = document.getElementById('generateAdvancedChartBtn');
            
            if (themeSelect) themeSelect.addEventListener('change', changeTheme);
            if (exportDataBtn) exportDataBtn.addEventListener('click', exportData);
            if (saveTemplateBtn) saveTemplateBtn.addEventListener('click', saveTemplate);
            if (loadTemplateBtn) loadTemplateBtn.addEventListener('click', loadTemplate);
            if (applyCleaningBtn) applyCleaningBtn.addEventListener('click', applyCleaning);
            if (generateStatsBtn) generateStatsBtn.addEventListener('click', generateStatistics);
            if (exportDataBtnAdvanced) exportDataBtnAdvanced.addEventListener('click', exportDataAdvanced);
            if (generateAdvancedChartBtn) generateAdvancedChartBtn.addEventListener('click', generateAdvancedChart);

            // History handlers - with null checks
            const loadHistoryBtn = document.getElementById('loadHistoryBtn');
            const clearHistoryBtn = document.getElementById('clearHistoryBtn');
            const historyDatasetSelect = document.getElementById('historyDatasetSelect');
            if (loadHistoryBtn) loadHistoryBtn.addEventListener('click', loadFromHistory);
            if (clearHistoryBtn) clearHistoryBtn.addEventListener('click', clearHistory);
            if (historyDatasetSelect) historyDatasetSelect.addEventListener('change', onHistorySelectChange);

            // Floating history panel handlers - with null checks
            const toggleHistoryPanel = document.getElementById('toggleHistoryPanel');
            const refreshFloatingHistory = document.getElementById('refreshFloatingHistory');
            const clearAllFloatingHistory = document.getElementById('clearAllFloatingHistory');
            if (toggleHistoryPanel) toggleHistoryPanel.addEventListener('click', toggleFloatingHistoryPanel);
            if (refreshFloatingHistory) refreshFloatingHistory.addEventListener('click', refreshFloatingHistoryGrid);
            if (clearAllFloatingHistory) clearAllFloatingHistory.addEventListener('click', clearAllHistory);

            // Initialize floating panel dragging
            initializeFloatingPanelDrag();

            // Header dropdown handlers
            const advancedToolsBtn = document.getElementById('advancedToolsBtn');
            if (advancedToolsBtn) {
                advancedToolsBtn.addEventListener('click', toggleAdvancedToolsDropdown);
            }
            
            // Close dropdown when clicking outside
            document.addEventListener('click', function(e) {
                const dropdown = document.querySelector('.dropdown');
                if (dropdown && !dropdown.contains(e.target)) {
                    dropdown.classList.remove('active');
                }
            });

            // Delete confirmation handlers - with null checks
            const overlay = document.getElementById('overlay');
            if (overlay) overlay.addEventListener('click', cancelDelete);
            
            // ESC key handler for fullscreen and dialogs (only bind once)
            if (!document.xlcigKeyHandlerBound) {
                document.addEventListener('keydown', function(e) {
                    if (e.key === 'Escape') {
                        // Check for temporary fullscreen first
                        const tempFullscreen = document.querySelector('.fullscreen-dashboard.active:not(#fullscreenDashboard)');
                        if (tempFullscreen) {
                            closeTempFullscreen(tempFullscreen.querySelector('.fullscreen-close'));
                            return;
                        }
                        
                        // Check for main dashboard fullscreen
                        const fullscreenDashboard = document.getElementById('fullscreenDashboard');
                        if (fullscreenDashboard && fullscreenDashboard.classList.contains('active')) {
                            safeExitFullscreen();
                            return;
                        }
                        
                        // Handle delete dialog
                        cancelDelete();
                    }
                });
                document.xlcigKeyHandlerBound = true;
            }
        }

        // Internationalization functions
        function switchLanguage(lang) {
            currentLanguage = lang;
            updateLanguage(lang);
            
            // Update language buttons
            document.querySelectorAll('.lang-btn').forEach(btn => {
                btn.classList.toggle('active', btn.dataset.lang === lang);
            });
        }

        function updateLanguage(lang) {
            const texts = i18n[lang];
            
            // Update regular text elements
            document.querySelectorAll('[data-i18n]').forEach(element => {
                const key = element.dataset.i18n;
                if (texts[key]) {
                    element.textContent = texts[key];
                }
            });
            
            // Update SEO meta tags
            updateSEOTags(lang);
        }

        function updateSEOTags(lang) {
            const texts = i18n[lang];
            
            // Update document title
            if (texts['seo.title']) {
                document.title = texts['seo.title'];
                document.getElementById('page-title').textContent = texts['seo.title'];
            }
            
            // Update meta description
            if (texts['seo.description']) {
                const metaDesc = document.getElementById('page-description');
                if (metaDesc) metaDesc.setAttribute('content', texts['seo.description']);
            }
            
            // Update meta keywords
            if (texts['seo.keywords']) {
                const metaKeywords = document.getElementById('page-keywords');
                if (metaKeywords) metaKeywords.setAttribute('content', texts['seo.keywords']);
            }
            
            // Update Open Graph tags
            if (texts['seo.title']) {
                const ogTitle = document.getElementById('og-title');
                if (ogTitle) ogTitle.setAttribute('content', texts['seo.title']);
                
                const twitterTitle = document.getElementById('twitter-title');
                if (twitterTitle) twitterTitle.setAttribute('content', texts['seo.title']);
            }
            
            if (texts['seo.description']) {
                const ogDesc = document.getElementById('og-description');
                if (ogDesc) ogDesc.setAttribute('content', texts['seo.description']);
                
                const twitterDesc = document.getElementById('twitter-description');
                if (twitterDesc) twitterDesc.setAttribute('content', texts['seo.description']);
            }
            
            // Update language attribute
            document.documentElement.setAttribute('lang', lang);
            const metaLang = document.querySelector('meta[name="language"]');
            if (metaLang) metaLang.setAttribute('content', lang);
            
            // Update structured data
            updateStructuredData(lang);
        }

        function updateStructuredData(lang) {
            const texts = i18n[lang];
            const structuredData = {
                "@context": "https://schema.org",
                "@type": "SoftwareApplication",
                "name": texts['seo.title'] || "xlcig Notebook Enterprise Analytics",
                "description": texts['seo.description'] || "Professional data visualization platform",
                "url": window.location.origin,
                "applicationCategory": "BusinessApplication",
                "operatingSystem": "Web Browser",
                "inLanguage": lang,
                "offers": {
                    "@type": "Offer",
                    "price": "0",
                    "priceCurrency": "USD"
                },
                "creator": {
                    "@type": "Organization",
                    "name": "xlcig Team",
                    "url": window.location.origin
                },
                "featureList": [
                    "Data Visualization",
                    "Interactive Charts", 
                    "Dashboard Builder",
                    "CSV/Excel Import",
                    "Export Functionality",
                    "Multi-language Support"
                ]
            };
            
            // Update or create structured data script
            let structuredScript = document.querySelector('script[type="application/ld+json"]');
            if (structuredScript) {
                structuredScript.textContent = JSON.stringify(structuredData, null, 2);
            }
        }

        function t(key, ...args) {
            let text = i18n[currentLanguage][key] || key;
            args.forEach((arg, index) => {
                text = text.replace(`{${index}}`, arg);
            });
            return text;
        }

        // Sortable setup for drag and drop
        function setupSortable() {
            const chartsGrid = document.getElementById('chartsGrid');
            const customChartsGrid = document.getElementById('customChartsGrid');
            
            [chartsGrid, customChartsGrid].forEach(grid => {
                if (grid) {
                    new Sortable(grid, {
                        animation: 150,
                        ghostClass: 'sortable-ghost',
                        chosenClass: 'sortable-chosen',
                        dragClass: 'sortable-drag',
                        handle: '.drag-handle',
                        onStart: function(evt) {
                            evt.item.classList.add('dragging');
                        },
                        onEnd: function(evt) {
                            evt.item.classList.remove('dragging');
                            // Save new order if needed
                            saveChartOrder();
                        }
                    });
                }
            });
        }

        function saveChartOrder() {
            // Implementation for saving chart order
            console.log('Chart order saved');
        }

        function handleFileSelection(files) {
            // Prevent file selection during processing
            if (isProcessing) {
                updateStatus(t('upload.processing_wait'), 'warning');
                return;
            }
            
            selectedFiles = Array.from(files);
            updateFileList();
            updateProcessButton();
        }

        function updateFileList() {
            if (selectedFiles.length === 0) {
                fileList.style.display = 'none';
                return;
            }

            fileList.style.display = 'block';
            fileList.innerHTML = '';

            selectedFiles.forEach((file, index) => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <span><i class="fas fa-file"></i> ${file.name}</span>
                    <span>${formatFileSize(file.size)}</span>
                `;
                fileList.appendChild(fileItem);
            });
        }

        function updateProcessButton() {
            processBtn.disabled = selectedFiles.length === 0;
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function updateStatus(message, type = 'info', useI18n = false) {
            let displayMessage = message;
            
            if (useI18n && typeof message === 'object') {
                displayMessage = t(message.key, ...message.args);
            }
            
            statusDisplay.textContent = displayMessage;
            statusDisplay.className = `status-display status-${type}`;
            
            // Update i18n attribute if using internationalization
            if (useI18n && typeof message === 'object') {
                statusDisplay.setAttribute('data-i18n', message.key);
            } else {
                statusDisplay.removeAttribute('data-i18n');
            }
        }

        async function handleAnalyzeClick() {
            // Prevent multiple concurrent operations
            if (isProcessing) {
                updateStatus(t('upload.processing_wait'), 'warning');
                return;
            }
            
            if (currentSessionId && sessionData) {
                // Data already uploaded, just analyze and show results
                await analyzeData();
            } else {
                // No data yet, process files first
                await processFiles();
            }
        }

        async function analyzeData() {
            if (!currentSessionId) {
                // No session, need to upload files first
                updateStatus(t('upload.session_expired'), 'warning');
                await processFiles();
                return;
            }
            
            try {
                // Set processing state
                isProcessing = true;
                processBtn.disabled = true;
                processBtn.innerHTML = `<span class="loading"></span> ${t('upload.processing')}`;
                updateStatus(t('upload.processing'), 'warning');

                // Call analyze API
                const response = await fetch(`/api/analyze/${currentSessionId}`, {
                    method: 'POST'
                });

                const result = await response.json();

                if (result.success) {
                    // Update session data with charts
                    sessionData = result;
                    
                    // Show main content
                    welcomeScreen.style.display = 'none';
                    mainContent.style.display = 'block';
                    
                    // Show dashboard buttons with null checks
                    const dashboardBtn = document.getElementById('dashboardBtn');
                    const fullscreenBtn = document.getElementById('fullscreenBtn');
                    if (dashboardBtn) dashboardBtn.style.display = 'inline-flex';
                    if (fullscreenBtn) fullscreenBtn.style.display = 'inline-flex';
                    
                    // Show chart builder, history, and advanced features with null checks
                    if (chartBuilderSection) chartBuilderSection.style.display = 'block';
                    const historySection = document.getElementById('historySection');
                    const advancedSection = document.getElementById('advancedSection');
                    if (historySection) historySection.style.display = 'block';
                    if (advancedSection) advancedSection.style.display = 'block';
                    
                    // Display results
                    displayResults(result);
                    setupChartBuilder();
                    
                    // Populate advanced feature selects
                    populateAdvancedSelects();
                    
                    // Update button text
                    processBtn.innerHTML = `<i class="fas fa-sync-alt"></i> ${t('upload.reanalyze')}`;
                    updateStatus(t('upload.analysis_complete'), 'success');
                } else {
                    // Handle session not found error by re-uploading
                    if (result.error === 'Session not found') {
                        console.log('Session expired, re-uploading files...');
                        currentSessionId = null;
                        sessionData = null;
                        updateStatus(t('upload.session_expired'), 'warning');
                        
                        // Re-upload files
                        await processFiles();
                        return;
                    }
                    
                    updateStatus(t('upload.error') + ': ' + result.error, 'error');
                    console.error('Analysis error:', result);
                }

            } catch (error) {
                updateStatus(t('upload.error') + ': ' + error.message, 'error');
                console.error('Network error:', error);
            } finally {
                // Reset processing state
                isProcessing = false;
                
                // Only enable button if analysis failed
                if (!sessionData || !sessionData.charts || sessionData.charts.length === 0) {
                    processBtn.disabled = false;
                    processBtn.innerHTML = `<i class="fas fa-chart-line"></i> ${t('upload.analyze')}`;
                }
            }
        }

        async function processFiles() {
            if (selectedFiles.length === 0) return;
            
            // Prevent concurrent processing
            if (isProcessing) {
                updateStatus(t('upload.processing_wait'), 'warning');
                return;
            }

            // Prepare form data
            const formData = new FormData();
            selectedFiles.forEach(file => {
                formData.append('files', file);
            });

            try {
                // Set processing state
                isProcessing = true;
                processBtn.disabled = true;
                processBtn.innerHTML = `<span class="loading"></span> ${t('upload.processing')}`;
                updateStatus(t('upload.processing'), 'warning');

                // Upload and process files
                const response = await fetch('/api/upload', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.success) {
                    currentSessionId = result.session_id;
                    // Store basic upload info only (no charts)
                    sessionData = {
                        session_id: result.session_id,
                        file_info: result.file_info,
                        charts: [] // Empty initially
                    };
                    
                                    // Save to history cache
                saveToHistory(sessionData);
                updateHistoryList();
                refreshFloatingHistoryGrid();
                    
                    updateStatus(t('upload.success', result.file_count), 'success');
                    
                    // Change button to analyze mode
                    processBtn.innerHTML = `<i class="fas fa-chart-line"></i> ${t('upload.analyze')}`;
                    processBtn.disabled = false;
                    
                } else {
                    updateStatus(t('upload.error', result.error), 'error');
                    console.error('Processing error:', result);
                }

            } catch (error) {
                updateStatus(t('upload.error', error.message), 'error');
                console.error('Network error:', error);
            } finally {
                // Reset processing state
                isProcessing = false;
                
                // Only reset if there was an error
                if (!currentSessionId) {
                    processBtn.disabled = false;
                    processBtn.innerHTML = `<i class="fas fa-cogs"></i> ${t('upload.analyze')}`;
                }
            }
        }

        function displayResults(result) {
            // Display data summary
            displayDataSummary(result.file_info);

            // Display charts
            displayCharts(result.charts);
        }

        function displayDataSummary(fileInfo) {
            const tableBody = document.getElementById('summaryTableBody');
            tableBody.innerHTML = '';

            fileInfo.forEach(info => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td style="font-weight: 500;">${info.name}</td>
                    <td>${info.rows.toLocaleString()}</td>
                    <td>${info.columns}</td>
                    <td>${info.numeric_cols}</td>
                    <td>${info.categorical_cols}</td>
                    <td>${info.size}</td>
                `;
                tableBody.appendChild(row);
            });
        }

        function displayCharts(charts) {
            const chartsGrid = document.getElementById('chartsGrid');
            chartsGrid.innerHTML = '';

            charts.forEach(chart => {
                const chartCard = createChartCard(chart);
                chartsGrid.appendChild(chartCard);
            });
        }

        function createChartCard(chart) {
            const chartCard = document.createElement('div');
            chartCard.className = 'chart-card';
            chartCard.dataset.chartId = chart.id;
            chartCard.innerHTML = `
                <div class="chart-header">
                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                        <span class="drag-handle" title="${t('chart.drag_to_reorder')}">
                            <i class="fas fa-grip-vertical"></i>
                        </span>
                        <h4 class="chart-title">${chart.title}</h4>
                    </div>
                    <div class="chart-actions">
                        <button class="chart-btn" onclick="duplicateChart('${chart.id}')" title="${t('chart.duplicate')}">
                            <i class="fas fa-copy"></i>
                        </button>
                        <button class="chart-btn" onclick="editChart('${chart.id}')" title="${t('chart.edit')}">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="chart-btn" onclick="showDeleteConfirm('${chart.id}')" title="${t('chart.delete')}">
                            <i class="fas fa-trash"></i>
                        </button>
                        <button class="chart-btn" onclick="downloadChart('${chart.id}')" title="${t('chart.download')}">
                            <i class="fas fa-download"></i>
                        </button>
                        <button class="chart-btn" onclick="shareChart('${chart.id}')" title="${t('chart.share')}">
                            <i class="fas fa-share-alt"></i>
                        </button>
                        <button class="chart-btn" onclick="toggleFullscreenChart('${chart.id}')" title="${t('chart.fullscreen')}">
                            <i class="fas fa-expand"></i>
                        </button>
                    </div>
                </div>
                <div class="chart-body">
                    <div id="${chart.id}" class="chart-container"></div>
                </div>
            `;

            // Store chart data
            chartCard.chartData = chart;

            // Render chart after DOM insertion
            setTimeout(() => {
                renderEChart(chart.id, chart.config);
            }, 100);

            return chartCard;
        }

        function renderEChart(containerId, config) {
            try {
                const container = document.getElementById(containerId);
                if (!container) {
                    console.error(`Container ${containerId} not found`);
                    return;
                }

                // Ensure container has proper dimensions
                if (container.offsetWidth === 0 || container.offsetHeight === 0) {
                    // Wait for container to be properly sized
                    setTimeout(() => renderEChart(containerId, config), 200);
                    return;
                }

                // Dispose existing chart if any
                if (container.chartInstance) {
                    container.chartInstance.dispose();
                }

                const theme = document.body.getAttribute('data-theme');
                const chart = echarts.init(container, theme === 'dark' ? 'dark' : null, {
                    width: container.offsetWidth,
                    height: container.offsetHeight - 20, // Account for padding
                    renderer: 'canvas'
                });
                
                chart.setOption(config, true);

                // Resize immediately to ensure proper sizing
                setTimeout(() => {
                    if (chart && !chart.isDisposed()) {
                        chart.resize();
                    }
                }, 50);

                // Handle resize
                const resizeHandler = () => {
                    if (chart && !chart.isDisposed()) {
                        chart.resize();
                    }
                };
                
                window.addEventListener('resize', resizeHandler);

                // Store chart instance, config, and resize handler
                container.chartInstance = chart;
                container.chartOption = config;
                container.resizeHandler = resizeHandler;
                
            } catch (error) {
                console.error(`Error rendering chart ${containerId}:`, error);
                const container = document.getElementById(containerId);
                if (container) {
                    container.innerHTML = `<div style="padding: 2rem; text-align: center; color: #666;">
                        <i class="fas fa-exclamation-triangle"></i><br>
                        Chart rendering failed<br>
                        <small>${error.message}</small>
                    </div>`;
                }
            }
        }

        function switchTab(tabName) {
            // Update tab buttons
            document.querySelectorAll('.tab-button').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

            // Update tab panes
            document.querySelectorAll('.tab-pane').forEach(pane => {
                pane.classList.remove('active');
            });
            document.getElementById(`${tabName}-tab`).classList.add('active');
        }

        async function setupChartBuilder() {
            if (!currentSessionId) return;

            // Populate dataset dropdown
            datasetSelect.innerHTML = `<option value="">${t('builder.select_dataset')}</option>`;
            sessionData.file_info.forEach(info => {
                const option = document.createElement('option');
                option.value = info.name;
                option.textContent = info.name;
                datasetSelect.appendChild(option);
            });
        }

        async function onDatasetChange() {
            const dataset = datasetSelect.value;
            if (!dataset || !currentSessionId) return;

            try {
                const response = await fetch(`/api/chart-types/${currentSessionId}/${dataset}`);
                const result = await response.json();

                if (result.success) {
                    // Populate chart types
                    chartTypeSelect.innerHTML = `<option value="">${t('builder.select_chart_type')}</option>`;
                    result.chart_types.forEach(type => {
                        const option = document.createElement('option');
                        option.value = type.type;
                        const localizedName = t(`chart_types.${type.type}`) || type.name;
                        option.textContent = localizedName + (type.recommended ? ' ⭐' : '');
                        chartTypeSelect.appendChild(option);
                    });

                    // Populate column dropdowns
                    xAxisSelect.innerHTML = `<option value="">${t('builder.select_column')}</option>`;
                    yAxisSelect.innerHTML = `<option value="">${t('builder.select_column')}</option>`;

                    result.columns.all.forEach(col => {
                        const xOption = document.createElement('option');
                        xOption.value = col;
                        xOption.textContent = col;
                        xAxisSelect.appendChild(xOption);
                    });

                    result.columns.numeric.forEach(col => {
                        const yOption = document.createElement('option');
                        yOption.value = col;
                        yOption.textContent = col;
                        yAxisSelect.appendChild(yOption);
                    });
                }
            } catch (error) {
                console.error('Error loading chart types:', error);
            }
        }

        function onChartTypeChange() {
            // Enable/disable axis selectors based on chart type
            const chartType = chartTypeSelect.value;
            
            if (['heatmap', 'radar'].includes(chartType)) {
                xAxisSelect.disabled = true;
                yAxisSelect.disabled = true;
            } else if (['histogram', 'pie'].includes(chartType)) {
                xAxisSelect.disabled = false;
                yAxisSelect.disabled = true;
            } else {
                xAxisSelect.disabled = false;
                yAxisSelect.disabled = false;
            }
        }

        async function generateCustomChart() {
            if (isProcessing) {
                alert(t('upload.processing_wait'));
                return;
            }
            
            const dataset = datasetSelect.value;
            const chartType = chartTypeSelect.value;
            const xCol = xAxisSelect.value || null;
            const yCol = yAxisSelect.value || null;

            if (!dataset || !chartType || !currentSessionId) {
                alert(t('alert.select_dataset_chart'));
                return;
            }

            try {
                isProcessing = true;
                generateChartBtn.disabled = true;
                generateChartBtn.innerHTML = `<span class="loading"></span> ${t('builder.generating')}...`;
                const response = await fetch('/api/generate-chart', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        session_id: currentSessionId,
                        dataset: dataset,
                        chart_type: chartType,
                        x_col: xCol,
                        y_col: yCol
                    })
                });

                const result = await response.json();

                if (result.success) {
                    // Add to custom charts
                    customCharts.push(result);
                    
                    // Display in builder tab
                    const customGrid = document.getElementById('customChartsGrid');
                    const chartCard = createChartCard(result);
                    customGrid.appendChild(chartCard);
                    
                    // Switch to builder tab
                    switchTab('builder');
                } else {
                    alert(t('upload.error', result.message));
                }
            } catch (error) {
                console.error('Error generating chart:', error);
                alert(t('alert.chart_generation_error'));
            } finally {
                isProcessing = false;
                generateChartBtn.disabled = false;
                generateChartBtn.innerHTML = `<i class="fas fa-plus"></i> ${t('builder.generate')}`;
            }
        }

        // Safe wrapper for enter fullscreen
        function safeEnterFullscreen() {
            try {
                // Check if already in fullscreen mode
                const fullscreenDashboard = document.getElementById('fullscreenDashboard');
                if (fullscreenDashboard && fullscreenDashboard.classList.contains('active')) {
                    console.log('Already in fullscreen mode');
                    return;
                }
                
                enterFullscreen();
            } catch (error) {
                console.error('Enter fullscreen error:', error);
                alert(t('alert.fullscreen_error') || 'Failed to enter fullscreen mode');
            }
        }

        function enterFullscreen() {
            const fullscreenDashboard = document.getElementById('fullscreenDashboard');
            const fullscreenGrid = document.getElementById('fullscreenGrid');
            
            if (!fullscreenDashboard || !fullscreenGrid) {
                console.error('Fullscreen elements not found');
                return;
            }
            
            // Reset any previous state
            fullscreenDashboard.classList.remove('active');
            fullscreenGrid.innerHTML = '';
            
            // Show fullscreen dashboard
            fullscreenDashboard.style.display = 'block';
            fullscreenDashboard.classList.add('active');
            
            // Get all charts from current tab
            const activeTab = document.querySelector('.tab-pane.active');
            const charts = activeTab ? activeTab.querySelectorAll('.chart-container') : [];
            
            fullscreenGrid.innerHTML = '';
            
            if (charts.length === 0) {
                fullscreenGrid.innerHTML = `
                    <div style="display: flex; align-items: center; justify-content: center; height: 100%; color: white;">
                        <div style="text-align: center;">
                            <i class="fas fa-chart-area" style="font-size: 3rem; margin-bottom: 1rem;"></i>
                            <p style="margin: 0; font-size: 1.1rem;">${t('fullscreen.no_charts') || 'No charts available for fullscreen display'}</p>
                            <p style="margin: 0.5rem 0 0 0; font-size: 0.9rem; opacity: 0.7;">${t('fullscreen.upload_hint') || 'Please upload data and generate charts first'}</p>
                        </div>
                    </div>
                `;
                return;
            }
            
            charts.forEach((chart, index) => {
                if (index < 6) { // Max 6 charts in fullscreen
                    const fullscreenChart = document.createElement('div');
                    fullscreenChart.className = 'fullscreen-chart';
                    fullscreenChart.id = `fullscreen-${chart.id}`;
                    fullscreenGrid.appendChild(fullscreenChart);
                    
                    // Copy chart configuration
                    setTimeout(() => {
                        if (chart.chartInstance && !chart.chartInstance.isDisposed()) {
                            try {
                                const newChart = echarts.init(fullscreenChart, 'dark', {
                                    width: fullscreenChart.offsetWidth,
                                    height: fullscreenChart.offsetHeight
                                });
                                const option = chart.chartInstance.getOption();
                                newChart.setOption(option, true);
                                
                                // Store instance for cleanup
                                fullscreenChart.chartInstance = newChart;
                                
                                // Resize after initialization
                                setTimeout(() => {
                                    if (newChart && !newChart.isDisposed()) {
                                        newChart.resize();
                                    }
                                }, 100);
                                
                            } catch (error) {
                                console.error('Error creating fullscreen chart:', error);
                                fullscreenChart.innerHTML = `
                                    <div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #999;">
                                        <div style="text-align: center;">
                                            <i class="fas fa-exclamation-triangle" style="font-size: 2rem; margin-bottom: 0.5rem;"></i>
                                            <p style="margin: 0;">Chart render failed</p>
                                        </div>
                                    </div>
                                `;
                            }
                        }
                    }, 100);
                }
            });
        }

        // Safe wrapper function for onclick
        function safeExitFullscreen() {
            try {
                // Check if we're actually in fullscreen mode
                const fullscreenDashboard = document.getElementById('fullscreenDashboard');
                if (!fullscreenDashboard || !fullscreenDashboard.classList.contains('active')) {
                    console.log('Not in fullscreen mode');
                    return;
                }
                
                // First, always close our custom fullscreen
                fullscreenDashboard.classList.remove('active');
                fullscreenDashboard.style.display = 'none';
                
                // Clean up charts
                const fullscreenGrid = document.getElementById('fullscreenGrid');
                if (fullscreenGrid) {
                    const charts = fullscreenGrid.querySelectorAll('.fullscreen-chart');
                    charts.forEach(chart => {
                        try {
                            if (chart.chartInstance && !chart.chartInstance.isDisposed()) {
                                chart.chartInstance.dispose();
                            }
                        } catch (chartError) {
                            console.log('Chart cleanup error:', chartError);
                        }
                    });
                    fullscreenGrid.innerHTML = '';
                }
                
                // Then handle browser fullscreen if needed
                exitBrowserFullscreen();
                
                console.log('Fullscreen exited successfully');
                
            } catch (error) {
                console.error('Safe exit fullscreen error:', error);
                // Force fallback cleanup
                forceExitFullscreen();
            }
        }

        // Separate function to handle browser fullscreen
        function exitBrowserFullscreen() {
            try {
                // Check if we're actually in browser fullscreen
                const inFullscreen = !!(document.fullscreenElement || 
                                       document.webkitFullscreenElement || 
                                       document.mozFullScreenElement || 
                                       document.msFullscreenElement);
                
                if (!inFullscreen) {
                    return; // Not in browser fullscreen, nothing to do
                }
                
                // Exit browser fullscreen
                const exitPromise = document.exitFullscreen ? document.exitFullscreen() :
                                  document.webkitExitFullscreen ? Promise.resolve(document.webkitExitFullscreen()) :
                                  document.mozCancelFullScreen ? Promise.resolve(document.mozCancelFullScreen()) :
                                  document.msExitFullscreen ? Promise.resolve(document.msExitFullscreen()) :
                                  null;
                
                if (exitPromise && typeof exitPromise.catch === 'function') {
                    exitPromise.catch(err => {
                        console.log('Browser fullscreen exit failed:', err);
                    });
                }
                
            } catch (error) {
                console.log('Browser fullscreen detection/exit error:', error);
                // Silently ignore
            }
        }

        // Emergency fallback function
        function forceExitFullscreen() {
            try {
                const fullscreenDashboard = document.getElementById('fullscreenDashboard');
                if (fullscreenDashboard) {
                    fullscreenDashboard.style.display = 'none';
                    fullscreenDashboard.classList.remove('active');
                    
                    const fullscreenGrid = document.getElementById('fullscreenGrid');
                    if (fullscreenGrid) {
                        fullscreenGrid.innerHTML = '';
                    }
                }
            } catch (error) {
                console.log('Force exit error:', error);
            }
        }

        // Safe function to close temporary fullscreen overlays
        function closeTempFullscreen(button) {
            try {
                const overlay = button.closest('.fullscreen-dashboard');
                if (overlay && overlay.id !== 'fullscreenDashboard') {
                    // Clean up any charts in the temp overlay
                    const tempCharts = overlay.querySelectorAll('[id*="chart"]');
                    tempCharts.forEach(chart => {
                        if (chart.chartInstance && !chart.chartInstance.isDisposed()) {
                            chart.chartInstance.dispose();
                        }
                    });
                    
                    // Safely remove the overlay
                    overlay.remove();
                }
            } catch (error) {
                console.error('Error closing temp fullscreen:', error);
                // Fallback: try to remove the overlay anyway
                try {
                    const overlay = button.closest('.fullscreen-dashboard');
                    if (overlay && overlay.id !== 'fullscreenDashboard') {
                        overlay.remove();
                    }
                } catch (fallbackError) {
                    console.error('Fallback removal failed:', fallbackError);
                }
            }
        }

        // History Cache Management Functions
        function saveToHistory(data) {
            try {
                const historyKey = 'xlcig_history_cache';
                const timestamp = new Date().toISOString();
                const historyItem = {
                    id: generateHistoryId(),
                    timestamp: timestamp,
                    displayName: generateHistoryDisplayName(data.file_info),
                    fileInfo: data.file_info,
                    sessionData: {
                        ...data,
                        // Don't save charts to reduce storage size
                        charts: []
                    }
                };
                
                // Get existing history
                let history = JSON.parse(localStorage.getItem(historyKey) || '[]');
                
                // Add new item to the beginning
                history.unshift(historyItem);
                
                // Keep only last 20 items
                history = history.slice(0, 20);
                
                // Save back to localStorage
                localStorage.setItem(historyKey, JSON.stringify(history));
                historyCache = history;
                
                console.log('Saved to history:', historyItem.displayName);
                
            } catch (error) {
                console.error('Failed to save to history:', error);
            }
        }

        function loadHistory() {
            try {
                const historyKey = 'xlcig_history_cache';
                const history = JSON.parse(localStorage.getItem(historyKey) || '[]');
                historyCache = history;
                return history;
            } catch (error) {
                console.error('Failed to load history:', error);
                return [];
            }
        }

        function updateHistoryList() {
            const historySelect = document.getElementById('historyDatasetSelect');
            const loadBtn = document.getElementById('loadHistoryBtn');
            
            if (!historySelect) return;
            
            const history = loadHistory();
            
            // Clear existing options
            historySelect.innerHTML = '';
            
            if (history.length === 0) {
                historySelect.innerHTML = '<option value="">' + t('history.no_history') + '</option>';
                if (loadBtn) loadBtn.disabled = true;
                return;
            }
            
            // Add default option
            historySelect.innerHTML = '<option value="">' + t('history.select_dataset') + '</option>';
            
            // Add history items
            history.forEach(item => {
                const option = document.createElement('option');
                option.value = item.id;
                option.textContent = `${item.displayName} (${formatHistoryDate(item.timestamp)})`;
                historySelect.appendChild(option);
            });
            
            if (loadBtn) loadBtn.disabled = !historySelect.value;
        }

        function onHistorySelectChange() {
            const historySelect = document.getElementById('historyDatasetSelect');
            const loadBtn = document.getElementById('loadHistoryBtn');
            
            if (loadBtn) {
                loadBtn.disabled = !historySelect.value;
            }
        }

        async function loadFromHistory() {
            if (isProcessing) {
                alert(t('upload.processing_wait'));
                return;
            }
            
            const historySelect = document.getElementById('historyDatasetSelect');
            const selectedId = historySelect.value;
            
            if (!selectedId) {
                alert(t('history.select_dataset_first') || 'Please select a dataset first');
                return;
            }
            
            try {
                isProcessing = true;
                showLoading();
                
                const history = loadHistory();
                const selectedItem = history.find(item => item.id === selectedId);
                
                if (!selectedItem) {
                    alert(t('history.dataset_not_found') || 'Selected dataset not found');
                    return;
                }
                
                // Simulate session restoration
                currentSessionId = generateSessionId();
                sessionData = {
                    ...selectedItem.sessionData,
                    session_id: currentSessionId
                };
                
                // Show main content
                const welcomeScreen = document.getElementById('welcomeScreen');
                const mainContent = document.getElementById('mainContent');
                if (welcomeScreen) welcomeScreen.style.display = 'none';
                if (mainContent) mainContent.style.display = 'block';
                
                // Show sections
                if (chartBuilderSection) chartBuilderSection.style.display = 'block';
                const historySection = document.getElementById('historySection');
                const advancedSection = document.getElementById('advancedSection');
                const headerToolsSection = document.getElementById('headerToolsSection');
                if (historySection) historySection.style.display = 'block';
                if (advancedSection) advancedSection.style.display = 'block';
                if (headerToolsSection) headerToolsSection.style.display = 'block';
                
                // Show dashboard buttons
                const dashboardBtn = document.getElementById('dashboardBtn');
                const fullscreenBtn = document.getElementById('fullscreenBtn');
                if (dashboardBtn) dashboardBtn.style.display = 'inline-flex';
                if (fullscreenBtn) fullscreenBtn.style.display = 'inline-flex';
                
                // Populate header dropdowns
                populateHeaderDropdowns();
                
                // Display data summary
                displayDataSummary(selectedItem.fileInfo);
                
                // Setup chart builder
                setupChartBuilder();
                populateAdvancedSelects();
                
                // Update status
                updateStatus(t('history.loaded_successfully') + ': ' + selectedItem.displayName, 'success');
                
                // Update process button
                processBtn.innerHTML = `<i class="fas fa-chart-line"></i> ${t('upload.analyze')}`;
                processBtn.disabled = false;
                
                hideLoading();
                
            } catch (error) {
                hideLoading();
                console.error('Failed to load from history:', error);
                alert(t('history.load_failed') || 'Failed to load dataset from history');
            } finally {
                isProcessing = false;
            }
        }

        function clearHistory() {
            if (confirm(t('history.confirm_clear') || 'Are you sure you want to clear all history? This cannot be undone.')) {
                try {
                    const historyKey = 'xlcig_history_cache';
                    localStorage.removeItem(historyKey);
                    historyCache = [];
                    updateHistoryList();
                    updateStatus(t('history.cleared') || 'History cleared successfully', 'success');
                } catch (error) {
                    console.error('Failed to clear history:', error);
                    alert(t('history.clear_failed') || 'Failed to clear history');
                }
            }
        }

        // Helper functions for history
        function generateHistoryId() {
            return 'hist_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        function generateSessionId() {
            return 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        function generateHistoryDisplayName(fileInfo) {
            if (!fileInfo || fileInfo.length === 0) {
                return 'Unknown Dataset';
            }
            
            if (fileInfo.length === 1) {
                return fileInfo[0].name;
            }
            
            return `${fileInfo.length} datasets (${fileInfo[0].name}...)`;
        }

        function formatHistoryDate(timestamp) {
            try {
                const date = new Date(timestamp);
                const now = new Date();
                const diffMs = now - date;
                const diffMins = Math.floor(diffMs / 60000);
                const diffHours = Math.floor(diffMs / 3600000);
                const diffDays = Math.floor(diffMs / 86400000);
                
                if (diffMins < 1) return t('history.just_now') || 'just now';
                if (diffMins < 60) return `${diffMins}${t('history.mins_ago') || ' mins ago'}`;
                if (diffHours < 24) return `${diffHours}${t('history.hours_ago') || ' hours ago'}`;
                if (diffDays < 7) return `${diffDays}${t('history.days_ago') || ' days ago'}`;
                
                return date.toLocaleDateString();
            } catch (error) {
                return timestamp.slice(0, 10);
            }
        }

        // Floating History Panel Functions
        function refreshFloatingHistoryGrid() {
            const history = loadHistory();
            updateFloatingHistoryGrid(history);
            updateHistoryList(); // Also update the sidebar dropdown
        }

        function updateFloatingHistoryGrid(history = null) {
            if (!history) {
                history = loadHistory();
            }

            const floatingHistoryGrid = document.getElementById('floatingHistoryGrid');
            const floatingHistoryCount = document.getElementById('floatingHistoryCount');
            const noFloatingHistoryMessage = document.getElementById('noFloatingHistoryMessage');

            if (!floatingHistoryGrid) return;

            // Update count
            if (floatingHistoryCount) floatingHistoryCount.textContent = `(${history.length})`;

            // Clear grid
            floatingHistoryGrid.innerHTML = '';

            if (history.length === 0) {
                if (noFloatingHistoryMessage) noFloatingHistoryMessage.style.display = 'block';
                return;
            }

            if (noFloatingHistoryMessage) noFloatingHistoryMessage.style.display = 'none';

            // Create history items
            history.forEach((item, index) => {
                const historyItem = createFloatingHistoryItem(item, index);
                floatingHistoryGrid.appendChild(historyItem);
            });
        }

        function createFloatingHistoryItem(item, index) {
            const div = document.createElement('div');
            div.className = 'floating-history-item';
            div.dataset.historyId = item.id;

            const fileCount = item.fileInfo ? item.fileInfo.length : 0;
            const totalRows = item.fileInfo ? item.fileInfo.reduce((sum, file) => sum + (file.rows || 0), 0) : 0;
            const totalCols = item.fileInfo ? item.fileInfo.reduce((sum, file) => sum + (file.columns || 0), 0) : 0;

            div.innerHTML = `
                <div class="floating-item-header">
                    <h4 class="floating-item-title">${item.displayName}</h4>
                    <span class="floating-item-date">${formatHistoryDate(item.timestamp)}</span>
                </div>
                <div class="floating-item-info">
                    <span class="floating-info-tag">
                        <i class="fas fa-file"></i> ${fileCount} ${t('history.files') || 'files'}
                    </span>
                    <span class="floating-info-tag">
                        <i class="fas fa-table"></i> ${totalRows} ${t('history.rows') || 'rows'}
                    </span>
                    <span class="floating-info-tag">
                        <i class="fas fa-columns"></i> ${totalCols} ${t('history.columns') || 'columns'}
                    </span>
                </div>
                <div class="floating-item-actions">
                    <button class="btn btn-primary" onclick="loadFloatingHistoryItem('${item.id}')">
                        <i class="fas fa-chart-line"></i> <span data-i18n="history.visualize">Visualize</span>
                    </button>
                    <button class="btn btn-outline" onclick="deleteFloatingHistoryItem('${item.id}')">
                        <i class="fas fa-trash"></i> <span data-i18n="history.delete">Delete</span>
                    </button>
                </div>
            `;

            // Add click handler for selection
            div.addEventListener('click', (e) => {
                if (!e.target.closest('button')) {
                    selectFloatingHistoryItem(item.id);
                }
            });

            return div;
        }

        function selectFloatingHistoryItem(historyId) {
            // Remove selection from all items
            document.querySelectorAll('.floating-history-item').forEach(item => {
                item.classList.remove('selected');
            });

            // Add selection to clicked item
            const clickedItem = document.querySelector(`[data-history-id="${historyId}"]`);
            if (clickedItem) {
                clickedItem.classList.add('selected');
            }
        }

        function toggleFloatingHistoryPanel() {
            const panel = document.getElementById('floatingHistoryPanel');
            const toggleBtn = document.getElementById('toggleHistoryPanel');
            
            if (panel && toggleBtn) {
                const isCollapsed = panel.classList.contains('collapsed');
                
                if (isCollapsed) {
                    panel.classList.remove('collapsed');
                    toggleBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
                } else {
                    panel.classList.add('collapsed');
                    toggleBtn.innerHTML = '<i class="fas fa-history"></i>';
                }
            }
        }

        // Floating panel drag functionality
        function initializeFloatingPanelDrag() {
            const panel = document.getElementById('floatingHistoryPanel');
            const header = panel.querySelector('.floating-panel-header');
            
            if (!panel || !header) return;

            let isDragging = false;
            let currentX;
            let currentY;
            let initialX;
            let initialY;
            let xOffset = 0;
            let yOffset = 0;

            header.addEventListener('mousedown', dragStart);
            document.addEventListener('mousemove', drag);
            document.addEventListener('mouseup', dragEnd);

            function dragStart(e) {
                if (e.target.closest('.panel-btn')) return; // Don't drag when clicking buttons
                
                initialX = e.clientX - xOffset;
                initialY = e.clientY - yOffset;

                if (e.target === header || header.contains(e.target)) {
                    isDragging = true;
                    panel.classList.add('dragging');
                }
            }

            function drag(e) {
                if (isDragging) {
                    e.preventDefault();
                    
                    currentX = e.clientX - initialX;
                    currentY = e.clientY - initialY;

                    xOffset = currentX;
                    yOffset = currentY;

                    // Constrain to viewport
                    const rect = panel.getBoundingClientRect();
                    const maxX = window.innerWidth - rect.width;
                    const maxY = window.innerHeight - rect.height;
                    
                    currentX = Math.max(0, Math.min(currentX, maxX));
                    currentY = Math.max(0, Math.min(currentY, maxY));

                    panel.style.transform = `translate(${currentX}px, ${currentY}px)`;
                }
            }

            function dragEnd(e) {
                if (isDragging) {
                    isDragging = false;
                    panel.classList.remove('dragging');
                }
            }
        }

        async function loadFloatingHistoryItem(historyId) {
            if (isProcessing) {
                alert(t('upload.processing_wait'));
                return;
            }

            try {
                isProcessing = true;
                showLoading();

                const history = loadHistory();
                const selectedItem = history.find(item => item.id === historyId);

                if (!selectedItem) {
                    alert(t('history.dataset_not_found') || 'Selected dataset not found');
                    return;
                }

                // Create a new session by re-uploading the data
                updateStatus(t('history.loading') || 'Loading dataset from history...', 'info');
                
                // First, we need to recreate the files and upload them
                // For now, we'll simulate this by setting up the UI and session
                currentSessionId = null;
                sessionData = {
                    ...selectedItem.sessionData,
                    session_id: null
                };

                // Show main content and sections
                const welcomeScreen = document.getElementById('welcomeScreen');
                const mainContent = document.getElementById('mainContent');
                if (welcomeScreen) welcomeScreen.style.display = 'none';
                if (mainContent) mainContent.style.display = 'block';

                // Show sections
                if (chartBuilderSection) chartBuilderSection.style.display = 'block';
                const historySection = document.getElementById('historySection');
                const advancedSection = document.getElementById('advancedSection');
                const headerToolsSection = document.getElementById('headerToolsSection');
                if (historySection) historySection.style.display = 'block';
                if (advancedSection) advancedSection.style.display = 'block';
                if (headerToolsSection) headerToolsSection.style.display = 'block';

                // Show dashboard buttons
                const dashboardBtn = document.getElementById('dashboardBtn');
                const fullscreenBtn = document.getElementById('fullscreenBtn');
                if (dashboardBtn) dashboardBtn.style.display = 'inline-flex';
                if (fullscreenBtn) fullscreenBtn.style.display = 'inline-flex';

                // Display data summary
                displayDataSummary(selectedItem.fileInfo);
                
                // Switch to charts tab
                switchTab('charts');

                // Setup chart builder and advanced sections
                setupChartBuilder();
                populateAdvancedSelects();
                populateHeaderDropdowns();

                // For history items, show a message that they need to re-upload for full functionality
                updateStatus(t('history.loaded_from_cache') || 'Dataset loaded from cache. Upload files again for full analysis.', 'warning');

                hideLoading();

            } catch (error) {
                hideLoading();
                console.error('Failed to load floating history item:', error);
                alert(t('history.load_failed') || 'Failed to load dataset from history');
            } finally {
                isProcessing = false;
            }
        }

        function deleteFloatingHistoryItem(historyId) {
            if (confirm(t('history.confirm_delete') || 'Are you sure you want to delete this dataset from history?')) {
                try {
                    const historyKey = 'xlcig_history_cache';
                    let history = JSON.parse(localStorage.getItem(historyKey) || '[]');
                    
                    // Remove the item
                    history = history.filter(item => item.id !== historyId);
                    
                    // Save back to localStorage
                    localStorage.setItem(historyKey, JSON.stringify(history));
                    historyCache = history;
                    
                    // Update displays
                    refreshFloatingHistoryGrid();
                    updateHistoryList();
                    
                    updateStatus(t('history.deleted') || 'Dataset deleted from history', 'success');
                } catch (error) {
                    console.error('Failed to delete floating history item:', error);
                    alert(t('history.delete_failed') || 'Failed to delete dataset from history');
                }
            }
        }

        function clearAllHistory() {
            if (confirm(t('history.confirm_clear') || 'Are you sure you want to clear all history? This cannot be undone.')) {
                try {
                    const historyKey = 'xlcig_history_cache';
                    localStorage.removeItem(historyKey);
                    historyCache = [];
                    
                    // Update displays
                    refreshFloatingHistoryGrid();
                    updateHistoryList();
                    
                    updateStatus(t('history.cleared') || 'History cleared successfully', 'success');
                } catch (error) {
                    console.error('Failed to clear all history:', error);
                    alert(t('history.clear_failed') || 'Failed to clear history');
                }
            }
        }

        // Header Tools Functions
        function toggleAdvancedToolsDropdown(e) {
            e.stopPropagation();
            const dropdown = document.querySelector('.dropdown');
            if (dropdown) {
                dropdown.classList.toggle('active');
            }
        }

        function populateHeaderDropdowns() {
            if (!sessionData || !sessionData.file_info) return;
            
            const cleaningSelect = document.getElementById('cleaningDatasetHeader');
            const statsSelect = document.getElementById('statsDatasetHeader');
            const exportSelect = document.getElementById('exportDatasetHeader');
            
            const options = sessionData.file_info.map(file => 
                `<option value="${file.name}">${file.name}</option>`
            ).join('');
            
            if (cleaningSelect) cleaningSelect.innerHTML = '<option value="" data-i18n="advanced.select_dataset">Select Dataset</option>' + options;
            if (statsSelect) statsSelect.innerHTML = '<option value="" data-i18n="advanced.select_dataset">Select Dataset</option>' + options;
            if (exportSelect) exportSelect.innerHTML = '<option value="" data-i18n="advanced.select_dataset">Select Dataset</option>' + options;
        }

        async function applyCleaningFromHeader() {
            const dataset = document.getElementById('cleaningDatasetHeader').value;
            const operation = document.getElementById('cleaningOperationHeader').value;
            
            if (!dataset || !operation) {
                alert(t('alert.select_dataset_operation') || 'Please select dataset and operation');
                return;
            }
            
            try {
                showLoading();
                const response = await fetch(`/api/data_cleaning/${currentSessionId}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ dataset, operation })
                });
                
                const result = await response.json();
                hideLoading();
                
                if (result.success) {
                    alert(`${t('alert.cleaning_success') || 'Cleaning successful'}: ${result.message}`);
                    updateDatasetInfo(result.updated_info);
                    showDataTable(result.preview, dataset);
                } else {
                    alert(`${t('alert.cleaning_error') || 'Cleaning error'}: ${result.error}`);
                }
            } catch (error) {
                hideLoading();
                console.error('Cleaning error:', error);
                alert(t('alert.network_error') || 'Network error');
            }
        }

        async function generateStatsFromHeader() {
            const dataset = document.getElementById('statsDatasetHeader').value;
            
            if (!dataset) {
                alert(t('alert.select_dataset') || 'Please select a dataset');
                return;
            }
            
            try {
                showLoading();
                const response = await fetch(`/api/statistical_analysis/${currentSessionId}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ dataset })
                });
                
                const result = await response.json();
                hideLoading();
                
                if (result.success) {
                    displayStatisticsReport(result.statistics);
                    showDataTable(result.preview, dataset);
                } else {
                    alert(`${t('alert.stats_error') || 'Statistics error'}: ${result.error}`);
                }
            } catch (error) {
                hideLoading();
                console.error('Statistics error:', error);
                alert(t('alert.network_error') || 'Network error');
            }
        }

        async function exportDataFromHeader() {
            const dataset = document.getElementById('exportDatasetHeader').value;
            const format = document.getElementById('exportFormatHeader').value;
            
            if (!dataset) {
                alert(t('alert.select_dataset') || 'Please select a dataset');
                return;
            }
            
            try {
                showLoading();
                const response = await fetch(`/api/export_data/${currentSessionId}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ dataset, format })
                });
                
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${dataset}.${format === 'excel' ? 'xlsx' : format}`;
                    a.click();
                    window.URL.revokeObjectURL(url);
                    hideLoading();
                    alert(t('alert.export_success') || 'Export successful');
                } else {
                    const result = await response.json();
                    hideLoading();
                    alert(`${t('alert.export_error') || 'Export error'}: ${result.error}`);
                }
            } catch (error) {
                hideLoading();
                console.error('Export error:', error);
                alert(t('alert.network_error') || 'Network error');
            }
        }

        function showDataTable(data, datasetName) {
            if (!data || data.length === 0) return;
            
            const tableContainer = document.getElementById('dataVisualizationTable');
            const dataTableContainer = document.getElementById('dataTableContainer');
            const currentTableDataset = document.getElementById('currentTableDataset');
            
            if (!tableContainer || !dataTableContainer) return;
            
            // Show table
            tableContainer.style.display = 'block';
            
            // Update dataset name
            if (currentTableDataset) {
                currentTableDataset.textContent = `(${datasetName})`;
            }
            
            // Generate table HTML
            const headers = Object.keys(data[0]);
            const tableHTML = `
                <table class="data-table">
                    <thead>
                        <tr>
                            ${headers.map(header => `<th>${header}</th>`).join('')}
                        </tr>
                    </thead>
                    <tbody>
                        ${data.slice(0, 50).map(row => 
                            `<tr>${headers.map(header => `<td>${row[header] || ''}</td>`).join('')}</tr>`
                        ).join('')}
                    </tbody>
                </table>
                ${data.length > 50 ? `<p style="text-align: center; color: var(--text-secondary); margin-top: 10px;">Showing first 50 rows of ${data.length} total rows</p>` : ''}
            `;
            
            dataTableContainer.innerHTML = tableHTML;
            
            // Switch to builder tab to show the table
            switchTab('builder');
        }

        function exitFullscreen() {
            // Handle custom fullscreen dashboard
            const fullscreenDashboard = document.getElementById('fullscreenDashboard');
            if (fullscreenDashboard && fullscreenDashboard.classList.contains('active')) {
                fullscreenDashboard.classList.remove('active');
                
                // Clean up fullscreen charts
                const fullscreenGrid = document.getElementById('fullscreenGrid');
                if (fullscreenGrid) {
                    const charts = fullscreenGrid.querySelectorAll('.fullscreen-chart');
                    charts.forEach(chart => {
                        if (chart.chartInstance && !chart.chartInstance.isDisposed()) {
                            chart.chartInstance.dispose();
                        }
                    });
                    fullscreenGrid.innerHTML = '';
                }
            }
            
            // Also close any temporary fullscreen overlays
            document.querySelectorAll('.fullscreen-dashboard.active').forEach(overlay => {
                if (overlay.id !== 'fullscreenDashboard') {
                    overlay.remove();
                }
            });
            
            // Handle browser fullscreen separately
            exitBrowserFullscreen();
        }

        function showDashboard() {
            switchTab('charts');
        }

        // Delete confirmation functions
        function showDeleteConfirm(chartId) {
            pendingDeleteChart = chartId;
            document.getElementById('overlay').classList.add('show');
            document.getElementById('deleteConfirm').classList.add('show');
        }

        function cancelDelete() {
            pendingDeleteChart = null;
            document.getElementById('overlay').classList.remove('show');
            document.getElementById('deleteConfirm').classList.remove('show');
        }

        function confirmDelete() {
            if (pendingDeleteChart) {
                removeChart(pendingDeleteChart);
                cancelDelete();
            }
        }

        // Chart actions
        function duplicateChart(chartId) {
            const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
            if (chartCard && chartCard.chartData) {
                const originalChart = chartCard.chartData;
                const duplicatedChart = {
                    ...originalChart,
                    id: originalChart.id + '_copy_' + Date.now(),
                    title: originalChart.title + ' (Copy)'
                };
                
                // Add to appropriate grid
                const activeTab = document.querySelector('.tab-pane.active');
                const grid = activeTab.querySelector('.dashboard-grid');
                if (grid) {
                    const newCard = createChartCard(duplicatedChart);
                    grid.appendChild(newCard);
                }
            }
        }

        function editChart(chartId) {
            // Switch to builder tab and populate with chart data
            switchTab('builder');
            
            const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
            if (chartCard && chartCard.chartData) {
                const chart = chartCard.chartData;
                
                // Populate form fields
                if (chart.dataset) datasetSelect.value = chart.dataset;
                if (chart.type) chartTypeSelect.value = chart.type;
                if (chart.x_col) xAxisSelect.value = chart.x_col;
                if (chart.y_col) yAxisSelect.value = chart.y_col;
                
                // Trigger change events to update dependent fields
                datasetSelect.dispatchEvent(new Event('change'));
                chartTypeSelect.dispatchEvent(new Event('change'));
            }
        }

        function removeChart(chartId) {
            const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
            if (chartCard) {
                // Add fade out animation
                chartCard.style.transition = 'all 0.3s ease';
                chartCard.style.opacity = '0';
                chartCard.style.transform = 'scale(0.8)';
                
                setTimeout(() => {
                    chartCard.remove();
                    
                    // Remove from arrays if it exists
                    const chartIndex = customCharts.findIndex(chart => chart.id === chartId);
                    if (chartIndex > -1) {
                        customCharts.splice(chartIndex, 1);
                    }
                }, 300);
            }
        }

        function toggleFullscreenChart(chartId) {
            const chartContainer = document.getElementById(chartId);
            if (chartContainer && chartContainer.chartInstance) {
                // Create a temporary fullscreen overlay for single chart
                const overlay = document.createElement('div');
                overlay.className = 'fullscreen-dashboard active';
                overlay.innerHTML = `
                    <div class="fullscreen-header">
                        <h1 class="fullscreen-title">${chartContainer.closest('.chart-card').querySelector('.chart-title').textContent}</h1>
                        <button class="fullscreen-close" onclick="closeTempFullscreen(this)">
                            <i class="fas fa-times"></i> ${t('fullscreen.exit')}
                        </button>
                    </div>
                    <div style="height: calc(100vh - 120px); padding: 1rem;">
                        <div id="temp-chart-container" style="width: 100%; height: 100%;"></div>
                    </div>
                `;
                
                document.body.appendChild(overlay);
                
                // Render chart in fullscreen
                setTimeout(() => {
                    const tempContainer = overlay.querySelector('#temp-chart-container');
                    const fullscreenChart = echarts.init(tempContainer, 'dark');
                    fullscreenChart.setOption(chartContainer.chartInstance.getOption());
                                 }, 100);
             }
         }

         // Advanced Features Functions
         function changeTheme() {
             const theme = document.getElementById('themeSelect').value;
             document.body.setAttribute('data-theme', theme);
             
             // Re-render all charts with new theme
             document.querySelectorAll('.chart-container').forEach(container => {
                 if (container.chartInstance) {
                     container.chartInstance.dispose();
                     const newChart = echarts.init(container, theme === 'dark' ? 'dark' : null);
                     // Re-apply the same option
                     if (container.chartOption) {
                         newChart.setOption(container.chartOption);
                         container.chartInstance = newChart;
                     }
                 }
             });
         }

         function exportData() {
             if (!sessionData) return;
             
             try {
                 // Create CSV content
                 let csvContent = '';
                 sessionData.file_info.forEach(info => {
                     csvContent += `Dataset: ${info.name}\n`;
                     csvContent += `Rows: ${info.rows}, Columns: ${info.columns}\n`;
                     csvContent += `Numeric Columns: ${info.numeric_cols}, Categorical: ${info.categorical_cols}\n`;
                     csvContent += `Size: ${info.size}\n\n`;
                 });
                 
                 // Download CSV
                 const blob = new Blob([csvContent], { type: 'text/csv' });
                 const url = window.URL.createObjectURL(blob);
                 const a = document.createElement('a');
                 a.href = url;
                 a.download = `data_analysis_${new Date().toISOString().slice(0, 10)}.csv`;
                 a.click();
                 window.URL.revokeObjectURL(url);
                 
             } catch (error) {
                 console.error('Export error:', error);
                 alert(t('alert.export_error'));
             }
         }

         function downloadChart(chartId) {
             const chartContainer = document.getElementById(chartId);
             if (chartContainer && chartContainer.chartInstance) {
                 try {
                     const dataURL = chartContainer.chartInstance.getDataURL({
                         type: 'png',
                         pixelRatio: 2,
                         backgroundColor: '#fff'
                     });
                     
                     const a = document.createElement('a');
                     a.href = dataURL;
                     a.download = `chart_${chartId}_${new Date().toISOString().slice(0, 10)}.png`;
                     a.click();
                 } catch (error) {
                     console.error('Download error:', error);
                     alert(t('alert.download_error'));
                 }
             }
         }

                 // Advanced Features Functions
        async function applyCleaning() {
            if (isProcessing) {
                alert(t('upload.processing_wait'));
                return;
            }
            
            const dataset = document.getElementById('cleaningDataset').value;
            const operation = document.getElementById('cleaningOperation').value;
            
            if (!dataset || !operation) {
                alert(t('alert.select_dataset_operation'));
                return;
            }
            
            try {
                isProcessing = true;
                showLoading();
                 const response = await fetch(`/api/data_cleaning/${currentSessionId}`, {
                     method: 'POST',
                     headers: { 'Content-Type': 'application/json' },
                     body: JSON.stringify({ dataset, operation })
                 });
                 
                 const result = await response.json();
                 hideLoading();
                 
                 if (result.success) {
                     alert(`${t('alert.cleaning_success')}: ${result.message}`);
                     // Update file info display
                     updateDatasetInfo(result.updated_info);
                     // Show data preview if needed
                     console.log('Data preview:', result.preview);
                 } else {
                     alert(`${t('alert.cleaning_error')}: ${result.error}`);
                 }
                         } catch (error) {
                hideLoading();
                console.error('Cleaning error:', error);
                alert(t('alert.network_error'));
            } finally {
                isProcessing = false;
            }
         }

                 async function generateStatistics() {
            if (isProcessing) {
                alert(t('upload.processing_wait'));
                return;
            }
            
            const dataset = document.getElementById('analysisDataset').value;
            
            if (!dataset) {
                alert(t('alert.select_dataset'));
                return;
            }
            
            try {
                isProcessing = true;
                showLoading();
                 const response = await fetch(`/api/statistical_analysis/${currentSessionId}`, {
                     method: 'POST',
                     headers: { 'Content-Type': 'application/json' },
                     body: JSON.stringify({ dataset })
                 });
                 
                 const result = await response.json();
                 hideLoading();
                 
                 if (result.success) {
                     // Create a new tab or modal to display statistics
                     displayStatisticsReport(result.statistics);
                 } else {
                     alert(`${t('alert.stats_error')}: ${result.error}`);
                 }
                         } catch (error) {
                hideLoading();
                console.error('Statistics error:', error);
                alert(t('alert.network_error'));
            } finally {
                isProcessing = false;
            }
         }

                 async function exportDataAdvanced() {
            if (isProcessing) {
                alert(t('upload.processing_wait'));
                return;
            }
            
            const dataset = document.getElementById('exportDataset').value;
            const format = document.getElementById('exportFormat').value;
            
            if (!dataset) {
                alert(t('alert.select_dataset'));
                return;
            }
            
            try {
                isProcessing = true;
                showLoading();
                 const response = await fetch(`/api/export_data/${currentSessionId}`, {
                     method: 'POST',
                     headers: { 'Content-Type': 'application/json' },
                     body: JSON.stringify({ dataset, format })
                 });
                 
                 if (response.ok) {
                     // Trigger file download
                     const blob = await response.blob();
                     const url = window.URL.createObjectURL(blob);
                     const a = document.createElement('a');
                     a.href = url;
                     a.download = `${dataset}.${format === 'excel' ? 'xlsx' : format}`;
                     a.click();
                     window.URL.revokeObjectURL(url);
                     hideLoading();
                     alert(t('alert.export_success'));
                 } else {
                     const result = await response.json();
                     hideLoading();
                     alert(`${t('alert.export_error')}: ${result.error}`);
                 }
                         } catch (error) {
                hideLoading();
                console.error('Export error:', error);
                alert(t('alert.network_error'));
            } finally {
                isProcessing = false;
            }
         }

                 async function generateAdvancedChart() {
            if (isProcessing) {
                alert(t('upload.processing_wait'));
                return;
            }
            
            const dataset = document.getElementById('advancedChartDataset').value;
            const chartType = document.getElementById('advancedChartType').value;
            
            if (!dataset || !chartType) {
                alert(t('alert.select_dataset_chart_type'));
                return;
            }
            
            try {
                isProcessing = true;
                showLoading();
                 const response = await fetch(`/api/advanced_charts/${currentSessionId}`, {
                     method: 'POST',
                     headers: { 'Content-Type': 'application/json' },
                     body: JSON.stringify({ dataset, chart_type: chartType })
                 });
                 
                 const result = await response.json();
                 hideLoading();
                 
                 if (result.success) {
                     // Add chart to custom charts tab
                     addCustomChart(result.chart);
                     // Switch to builder tab to show the new chart
                     switchTab('builder');
                     alert(t('alert.chart_generated'));
                 } else {
                     alert(`${t('alert.chart_error')}: ${result.error}`);
                 }
                         } catch (error) {
                hideLoading();
                console.error('Advanced chart error:', error);
                alert(t('alert.network_error'));
            } finally {
                isProcessing = false;
            }
         }

         function displayStatisticsReport(stats) {
             // Create a modal or popup to display statistics
             const modal = document.createElement('div');
             modal.style.cssText = `
                 position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                 background: rgba(0,0,0,0.8); z-index: 10000; display: flex;
                 align-items: center; justify-content: center; padding: 2rem;
             `;
             
             const content = document.createElement('div');
             content.style.cssText = `
                 background: white; border-radius: 8px; padding: 2rem;
                 max-width: 800px; max-height: 80vh; overflow-y: auto;
                 position: relative;
             `;
             
             content.innerHTML = `
                 <button onclick="this.closest('.modal').remove()" style="position: absolute; top: 1rem; right: 1rem; border: none; background: none; font-size: 1.5rem; cursor: pointer;">&times;</button>
                 <h2>${t('stats.title')}</h2>
                 
                 <h3>${t('stats.basic_info')}</h3>
                 <table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;">
                     <tr><td style="padding: 0.5rem; border: 1px solid #ddd;"><strong>${t('stats.total_rows')}:</strong></td><td style="padding: 0.5rem; border: 1px solid #ddd;">${stats.basic_info.total_rows}</td></tr>
                     <tr><td style="padding: 0.5rem; border: 1px solid #ddd;"><strong>${t('stats.total_columns')}:</strong></td><td style="padding: 0.5rem; border: 1px solid #ddd;">${stats.basic_info.total_columns}</td></tr>
                     <tr><td style="padding: 0.5rem; border: 1px solid #ddd;"><strong>${t('stats.memory_usage')}:</strong></td><td style="padding: 0.5rem; border: 1px solid #ddd;">${stats.basic_info.memory_usage}</td></tr>
                     <tr><td style="padding: 0.5rem; border: 1px solid #ddd;"><strong>${t('stats.null_values')}:</strong></td><td style="padding: 0.5rem; border: 1px solid #ddd;">${stats.basic_info.null_values}</td></tr>
                     <tr><td style="padding: 0.5rem; border: 1px solid #ddd;"><strong>${t('stats.duplicate_rows')}:</strong></td><td style="padding: 0.5rem; border: 1px solid #ddd;">${stats.basic_info.duplicate_rows}</td></tr>
                 </table>
                 
                 <h3>${t('stats.column_types')}</h3>
                 <p><strong>${t('stats.numeric')}:</strong> ${stats.column_types.numeric} | <strong>${t('stats.categorical')}:</strong> ${stats.column_types.categorical} | <strong>${t('stats.datetime')}:</strong> ${stats.column_types.datetime}</p>
                 
                 ${Object.keys(stats.missing_data).length > 0 ? `
                 <h3>${t('stats.missing_data')}</h3>
                 <table style="width: 100%; border-collapse: collapse; margin-bottom: 1rem;">
                     ${Object.entries(stats.missing_data).map(([col, data]) => 
                         `<tr><td style="padding: 0.5rem; border: 1px solid #ddd;"><strong>${col}:</strong></td><td style="padding: 0.5rem; border: 1px solid #ddd;">${data.count} (${data.percentage})</td></tr>`
                     ).join('')}
                 </table>
                 ` : ''}
             `;
             
             modal.appendChild(content);
             modal.className = 'modal';
             document.body.appendChild(modal);
         }

         function updateDatasetInfo(updatedInfo) {
             // Update the file info in the summary table
             const tableBody = document.getElementById('summaryTableBody');
             const rows = tableBody.querySelectorAll('tr');
             
             rows.forEach(row => {
                 const nameCell = row.querySelector('td:first-child');
                 if (nameCell && nameCell.textContent === updatedInfo.name) {
                     row.innerHTML = `
                         <td>${updatedInfo.name}</td>
                         <td>${updatedInfo.rows}</td>
                         <td>${updatedInfo.columns}</td>
                         <td>${updatedInfo.numeric_cols}</td>
                         <td>${updatedInfo.categorical_cols}</td>
                         <td>${updatedInfo.size}</td>
                     `;
                 }
             });
             
             // Update session data
             if (sessionData) {
                 const fileInfo = sessionData.file_info.find(info => info.name === updatedInfo.name);
                 if (fileInfo) {
                     Object.assign(fileInfo, updatedInfo);
                 }
             }
         }

         function populateAdvancedSelects() {
             // Populate dataset selects in advanced features
             const selects = [
                 'cleaningDataset',
                 'analysisDataset', 
                 'exportDataset',
                 'advancedChartDataset'
             ];
             
             selects.forEach(selectId => {
                 const select = document.getElementById(selectId);
                 if (select && sessionData) {
                     select.innerHTML = '<option value="">' + t('advanced.select_dataset') + '</option>';
                     sessionData.file_info.forEach(info => {
                         const option = document.createElement('option');
                         option.value = info.name;
                         option.textContent = info.name;
                         select.appendChild(option);
                     });
                 }
             });
         }

         function shareChart(chartId) {
             const chartCard = document.querySelector(`[data-chart-id="${chartId}"]`);
             if (chartCard) {
                 const title = chartCard.querySelector('.chart-title').textContent;
                 const shareData = {
                     title: `Data Visualization: ${title}`,
                     text: `Check out this data visualization created with xlcig Notebook Enterprise Analytics`,
                     url: window.location.href
                 };
                 
                 if (navigator.share) {
                     navigator.share(shareData);
                 } else {
                     // Fallback to copy to clipboard
                     const shareText = `${shareData.title}\n${shareData.text}\n${shareData.url}`;
                     navigator.clipboard.writeText(shareText).then(() => {
                         alert(t('alert.link_copied'));
                     });
                 }
             }
         }

         function saveTemplate() {
             if (!sessionData) return;
             
             try {
                 const template = {
                     id: Date.now(),
                     name: `Template_${new Date().toISOString().slice(0, 10)}`,
                     created: new Date().toISOString(),
                     charts: customCharts,
                     layout: 'grid'
                 };
                 
                 const templates = JSON.parse(localStorage.getItem('dashboard_templates') || '[]');
                 templates.push(template);
                 localStorage.setItem('dashboard_templates', JSON.stringify(templates));
                 
                 alert(t('alert.template_saved'));
             } catch (error) {
                 console.error('Save template error:', error);
                 alert(t('alert.save_error'));
             }
         }

         function loadTemplate() {
             try {
                 const templates = JSON.parse(localStorage.getItem('dashboard_templates') || '[]');
                 if (templates.length === 0) {
                     alert(t('alert.no_templates'));
                     return;
                 }
                 
                 // Create a simple template selector
                 let templateList = t('alert.select_template') + '\n\n';
                 templates.forEach((template, index) => {
                     templateList += `${index + 1}. ${template.name} (${new Date(template.created).toLocaleDateString()})\n`;
                 });
                 
                 const selection = prompt(templateList + '\n' + t('alert.enter_template_number'));
                 const templateIndex = parseInt(selection) - 1;
                 
                 if (templateIndex >= 0 && templateIndex < templates.length) {
                     const template = templates[templateIndex];
                     // Load template charts
                     customCharts = template.charts || [];
                     
                     // Render charts
                     const customGrid = document.getElementById('customChartsGrid');
                     customGrid.innerHTML = '';
                     customCharts.forEach(chart => {
                         const chartCard = createChartCard(chart);
                         customGrid.appendChild(chartCard);
                     });
                     
                     switchTab('builder');
                     alert(t('alert.template_loaded'));
                 }
             } catch (error) {
                 console.error('Load template error:', error);
                 alert(t('alert.load_error'));
             }
         }
     </script>
</body>
</html> 